android - 把原来的所有代码放入新建项目后SharedPreferences报错
PHP中文网
PHP中文网 2017-04-17 17:18:47
0
3
711

新建一个项目,包名与原来项目相同,再把原来所有项目复制过来,结果在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
 
 什么情况,求解,.代码是全部从原来复制过来的
PHP中文网
PHP中文网

认证0级讲师

reply all(3)
迷茫

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

小葫芦

MyApplication.instance() is replaced by Activity object

If there is none here, it is not recommended to pass it, but after passing the Context, which is the context, it can be converted if there is a Context. The code is as follows

((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~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template