Android SharedPreferences儲存資料的使用方法
阿新 • • 發佈:2019-01-25
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();
}
}