我看过这个示例https://stackoverflow.com/a/23024962/8341034,并试图在我的代码中重新创建它。所以我只是在他们的示例中使用了它们:
(这是在我的onCreate之前)
public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
然后在我的onCreate中拥有
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
example = findViewById(R.id.example);
example.setText(restoredText);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
我手动将textview放入xml布局中,我将其称为textview example
。我试图将名称保存在共享首选项中,并将其放入textview中。但是,当我运行我的应用程序时,出现错误。
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.app.supermarketaislefinder/com.app.supermarketaislefinder.create}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2016)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:160)
at com.app.supermarketaislefinder.create.<init>(create.java:63)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2007)
(蓝色下划线错误位于第63行,位于
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
我做错了什么?
ps(将来我要实现的目标是,在关闭该应用程序之前,屏幕上许多微调器中的数据将保存到共享的首选项中,然后在重新打开该应用程序时,将这些数据值放回到转盘。但这是不同的故事