SharedPreferences nullPointerException when saving strings

后端 未结 4 715
小鲜肉
小鲜肉 2021-01-26 10:50

I am working launcher for android. At the moment I am working for address book(yes I want to include it to my launcher), but I am getting NullPointerException. Here

相关标签:
4条回答
  • 2021-01-26 11:07

    The NPE is because Numbers is an Activity but doesn't have a valid context (or rather, it isn't one).

    It looks like what you have done is made your Numbers class extend Activity so that you can call getSharedPreferences on it. However you can't just new an Activity in Android, you have to create it according to the proper Activity life cycle.

    If you want to be able to call getSharedPreferences inside your number class, you can get rid of extends Activity, add a Context member variable, and initialize it in the constructor.

    public class Numbers
    {
         Context mContext;
         public Numbers(Context context)
         {
             mContext = context;
         }
    

    then you can call getSharedPreferences on it:

         pres = mContext.getSharedPreferences("1",0);
    
    0 讨论(0)
  • 2021-01-26 11:10

    Read this and this

    You have declared twice your SharedPreferences variable.

    Also you need to call getSharedPreference(String, int) only once, if you need to access a specific shared variable you need only pres.getString(label, default_value).

    0 讨论(0)
  • 2021-01-26 11:12

    If you use editor.putString(number,button);, 'number' is your key and 'button' is your default value.

    If you want to retrieve the value of 'number' in your SharedPreferences, you should call getString(key, defValue) as follow :

    return pres.getString(number, "");

    0 讨论(0)
  • 2021-01-26 11:27

    You can declare ShardPreference object twice. 1. class level 2. in adNumber().

    so, please remove one of that and declare like this with initiate.

    SharedPreferences pres = getApplicationContext().getSharedPreferences("MyPres", MODE_PRIVATE); 
    

    and used it anywhere is you declare it on class level.

    0 讨论(0)
提交回复
热议问题