1. 程式人生 > >Android SharedPreferences儲存資料的使用方法

Android SharedPreferences儲存資料的使用方法


public class Main extends Activity 

@Override 
public void onCreate(Bundle savedInstanceState) 

super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 


public void onClick_WriteData(View view) 

SharedPreferences mySharedPreferences = getSharedPreferences("test", 
Activity.MODE_PRIVATE); 
SharedPreferences.Editor editor = mySharedPreferences.edit(); 
editor.putString("name", "karl"); 
editor.putString("habit", "sleep"); 
editor.commit(); 
Toast.makeText(this, "資料成功寫入SharedPreferences!" , 
Toast.LENGTH_LONG).show(); 


public void onClick_ReadData(View view) 

SharedPreferences sharedPreferences = getSharedPreferences("test", 
Activity.MODE_PRIVATE); 
String name = sharedPreferences.getString("name", ""); 
String habit = sharedPreferences.getString("habit", ""); 

Toast.makeText(this, "讀取資料如下:"+"\n"+"name:" + name + "\n" + "habit:" + habit, 
Toast.LENGTH_LONG).show();