我正在编写一个应用程序,并努力使用SharedPreference保存列表。它宣布我的应用程序在运行我的应用程序时停止工作。请帮忙 !!这些是我的代码和我的logcat:
SharedPreferences SPre1 = getSharedPreferences(Context.MODE_PRIVATE);
Set<String> WorkListSet = SPre1.getStringSet("NOTES_SET", new HashSet<String>());
List<String> WorkList = new ArrayList<String>(WorkListSet);
public void Update1()
{
SharedPreferences.Editor Editor = SPre1.edit();
Set<String> WorkListSet = new HashSet<String>(WorkList);
Editor.putStringSet("NOTES_SET", WorkListSet);
Editor.apply();
}
private SharedPreferences getSharedPreferences(int modePrivate) {
return null;
}
Stacktrace
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set android.content.SharedPreferences.getStringSet(java.lang.String, java.util.Set)' on a null object reference
at com.newthingtank.along.hello.MainActivity.<init>(MainActivity.java:38)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 07
答案 0 :(得分:1)
在SharedPreferences
public static boolean saveArray() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putInt("Status_size", sKey.size());
for(int i=0;i<sKey.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, sKey.get(i));
}
return mEdit1.commit();
}
从SharedPreferences
public static void loadArray(Context mContext) {
SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
sKey.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
sKey.add(mSharedPreference1.getString("Status_" + i, null));
}
}
答案 1 :(得分:0)
private SharedPreferences getSharedPreferences(int modePrivate) {
return null;
}
您正在调用该方法,并且您只返回null。所以你实际上从来没有得到共享的首选项。
您需要一个上下文引用并在其上调用getSharedPreferences()
。您没有提供足够的信息来说明如何获取对上下文的引用,但任何Activity实例都足以作为上下文。