【发布时间】:2017-07-12 11:45:32
【问题描述】:
我只需将保存文件路径从一个活动传输到另一个活动,但在显示数据时它显示空值。
以下是在 SharedPreference 中存储数据的代码:-
SharedPreferences pref= getApplicationContext().getSharedPreferences("Recorder",0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("file_name",DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
editor.putString("file_path",Environment.getExternalStorageDirectory()+"/"+DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
从 sharedPreference 中检索数据:-
file_name = (TextView) findViewById(R.id.file_name);
file_path = (TextView) findViewById(R.id.file_path);
pref = getApplicationContext().getSharedPreferences("Recorder",0);
editor = pref.edit();
String fileName = pref.getString("file_name",null);
String filePath = pref.getString("file_path",null);
if(fileName != null){
file_name.setText(fileName);
}else{
file_name.append("");
}
if (filePath != null){
file_path.setText(filePath);
}else{
file_path.append("");
}
【问题讨论】:
-
添加 editor.apply();在将值置于偏好之后
-
是的,您可以,
editor.apply()是您所缺少的;尽管更好的方法是使用intent.putStringExtra() -
你也可以写
editor.commit();stroing the values to sharepreference
标签: java android android-activity sharedpreferences