SharedPreferences nullPointerException when saving strings

后端 未结 4 714
小鲜肉
小鲜肉 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);
    

提交回复
热议问题