如何解决从服务访问命名的共享首选项
我正在尝试从服务访问SharedPreference并收到一个错误,我在网络上的任何地方都找不到。任何帮助表示赞赏。谢谢。
code
sharedPref = getApplicationContext()。getSharedPreferences(“ FlutterSharedPreferences”,Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
2020-09-10 21:16:04.057 10186-10186/com.example.demo1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.demo1,PID: 10186
java.lang.RuntimeException: Unable to start service com.example.demo1.MorningReset@ce7eae1 with Intent { flg=0x4 cmp=com.example.demo1/.MorningReset (has extras) }: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.UserManager.isUserUnlockingOrUnlocked(int)' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3686)
at android.app.ActivityThread.access$1600(ActivityThread.java:199)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.UserManager.isUserUnlockingOrUnlocked(int)' on a null object reference
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:418)
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:404)
at android.content.Contextwrapper.getSharedPreferences(Contextwrapper.java:174)
at com.example.demo1.MorningReset.onStartCommand(MorningReset.java:25)
仅当从服务访问SharedPreference时,才会出现此错误。同一行代码在活动中可以正常工作。
解决方法
write data to shared preferences
SharedPreferences sharedPreferences =getSharedPreferences("MySharedPref",MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
myEdit.putString( "name",name.getText().toString());
myEdit.apply();
retrieve data from shared preferences
SharedPreferences sh = getSharedPreferences("MySharedPref",MODE_PRIVATE);
String name = sh.getString("name","");
name.setText(name);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。