新建一个项目,包名与原来项目相同,再把原来所有项目复制过来,结果在getSharedPreferences中报错.代码如下
public static String getSharePreStr(String field) {
String FILE = MyApplication.instance().getResources().getString(R.string.app_dir);
SharedPreferences sp = (SharedPreferences) MyApplication.instance().getSharedPreferences(FILE, 0);
String s = sp.getString(field, "");
return s;
}
开始的时候判断是否有缓存,第一个错误是
Attempt to invoke virtual method 'android.content.res.Resources com.fenghua.traffic.MyApplication.getResources()' on a null object reference
于是我把String FILE = MyApplication.instance().getResources().getString(R.string.app_dir);
换成了String FILE = "XXX";
这句没错了,然后再次运行,报错
Attempt to invoke virtual method 'android.content.SharedPreferences com.fenghua.traffic.MyApplication.getSharedPreferences(java.lang.String, int)' on a null object reference
什么情况,求解,.代码是全部从原来复制过来的
Obviously MyApplication.instance() is empty. Check to see if it has been initialized.
MyApplication.instance() is null and should be checked before calling. It is said to be a good habit and convenient for writing logs
Maybe you did not completely recompile the code? Delete the app and try rebuilding it
((getContext)Activity).getSharedPreferences......
Also, young people, when writing code in the future, you must consider the issue of reuse. If you use it in more than two places, you can create a new variable to assign a value, and then call it. Save resource usage. I can’t tell it now. I was like this at the beginning. Now that I’m working, I’m tired of making various changes after writing the code = =
If you still don’t know how, you can contact me on the site. If you have any questions in the future, you can ask me~
Accept it~