问题描述
我想使用SharedPreference将图像保存在android中.我有两个活动类,当我单击第一个活动的按钮时,它将调用第二个活动,第二个活动在列表视图中显示我的首选名称,并且还将android墙纸重置为我设置为首选墙纸的图像在第一个活动中.
I want to save images in android using SharedPreference. I have two activity classes, when I click the button of the first activity it will call the second activity and the second activity displays my preferred name in a list view and also resets the android wallpaper to the image that I had set as a preferred wallpaper in the first activity.
第二个活动的代码是:
public class PreferencesActivityTest extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString("PREF_USERNAME", "nothing");
String wallPaper = myPrefs.getString("PREFS_NAME", null);
if(wallPaper != null) {
try {
Bitmap bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper);
Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper);
setWallpaper(bm);
Toast.makeText(this, "Wall paper has been changed." +
"You may go to the home screen to view the same", Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException fe){
Log.e(getClass().getSimpleName(),"File not found");
} catch (IOException ie) {
Log.e(getClass().getSimpleName()," IO Exception");
}
}
ArrayList<String> results = new ArrayList<String>();
results.add("Your Preferred name is: " + prefName);
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
}
第一个活动调用第二个活动,但没有调用if(wallPaper != null){}
The first activity calls the second activity but it is not calling if(wallPaper != null){}
为什么不起作用?
推荐答案
不建议将图像存储在共享"首选项中,您应该将该图像存储到sdcard.然后将图像路径(来自sdcard)存储到共享"首选项中,如下所示: -
Its not recommended to store image in Share preferences And you should store that image to sdcard.And then store image path (from sdcard) into Share preferences like this--
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("imagepath","/sdcard/imh.jpeg");
edit.commit();
,然后使用此路径从sdcard获取图像
and then fetch image from sdcard by using this path
这篇关于如何在Android中使用SharedPreference存储图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!