【发布时间】:2023-03-09 20:02:01
【问题描述】:
我正在构建一个相机应用程序。我正在尝试使用 SharedPreferences 保存一些信息。 我想保存一些持久性信息 - 最后一张图像拍摄的文件路径。但是在拍照前第一次使用应用程序时,数据会为NULL。
所以我想在 onCreate 中 getSharedPreferences 并检查该值是否为空。但据我所知,使用 getSharedPreferences 的唯一方法是只有在您之前在编辑器上调用过 put 时。因此,我第一次在 SharedPreferences 对象上得到一个 NULL 指针异常。
你如何解决这个问题?
//inside on Create()
imageData = getSharedPreferences("ImageData",MODE_PRIVATE);
SharedPreferences.Editor prefEditor = imageData.edit();
prefEditor.commit();
String previousImage = imageData.getString("lastImageTaken", null);
if(previousImage == null){
Log.d(TAG,"previous image is NULL");
}
else{
//do something with the filepath
}
//-----------------------
//in onClick of capture button
imageData = getSharedPreferences("ImageData",MODE_PRIVATE);
SharedPreferences.Editor prefEditor = imageData.edit();
prefEditor.putString("lastImageTaken", MyActivity.this.pictureFilePath);
prefEditor.commit();
【问题讨论】:
-
你能解释一下
String previousImage,它在共享首选项中吗? -
SharedPreferences.Editor prefEditor = imageData.edit(); 有什么用prefEditor.commit();那些线?
-
你的代码不应该产生空指针异常,即使它产生了,它也与 SharedPreference 的不存在无关。发布您的堆栈跟踪,也许我们可以在那里找到一些东西。
-
@Pankaj:SharedPreferences 对象没有分配任何内存。我们不能说新的 SharedPreferences。它在文档中说,如果 getSharedPreferences 的第一个参数不存在,那么 edit() 调用将创建它。这就是为什么我试图把这两行放在为它分配内存的希望中。如果我错了,请纠正我。
-
@Namratha: 在
oncreate中显然它将为空,因为您试图检索从未放置过的东西
标签: android nullpointerexception sharedpreferences