Android应用开发SharedPreferences存储数据的使用方法

时间:2021-10-17 05:29:33

SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)。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(); 

} 
}