我正在尝试从共享首选项中获取用户想要的语言,并通过此答案来设置应用程序的语言。
我有与该答案相同的MyConxtextWrapper文件,但已将包装器注入更改为:
@Override
protected void attachBaseContext(Context newBase) {
SharedPreferences sharedPref = getSharedPreferences("userLang", Context.MODE_PRIVATE);
String lang = sharedPref.getString("lang", "");
super.attachBaseContext(MyContextWrapper.wrap(newBase,lang));
}
}
这给我带来了错误:
04-01 18:35:25.648 25032-25032/com.example.c1629177.cymruniapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.c1629177.cymruniapp, PID: 25032
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.c1629177.cymruniapp/com.example.c1629177.cymruniapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:171)
at com.example.c1629177.cymruniapp.MainActivity.attachBaseContext(MainActivity.java:194)
at android.app.Activity.attach(Activity.java:6175)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2350)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
如何将共享偏好值“lang”传递到行super.attachBaseContext(MyContextWrapper.wrap(newBase,lang));
中?