Android: NullPointerException Working With SharedPreferences

前端 未结 3 2026
北恋
北恋 2021-01-23 21:12

Working with SharedPreferences, this activity crashes upon launching. First I\'ll post the activity code, and then I\'ll post my LogCat. Thank you so much guys, you guys are alw

相关标签:
3条回答
  • 2021-01-23 21:19
    public class MainActivity extends Activity{
    
    SharedPreferences sharedpreferences;    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
    sharedpreferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);  
    
                editor.putBoolean("sharedpreferences", true);
                editor.commit();
    
    // your code ...
    
    }
    
    // your code ...
    }
    
    0 讨论(0)
  • 2021-01-23 21:23

    You have to access the shared preferences AFTER onCreate is called. Or else the context would be null :) that's why you're getting a null pointer exception

    move this line :

    SharedPreferences settings = getSharedPreferences("gBValues", 
         Context.MODE_PRIVATE);
    

    in the onCreate()

    0 讨论(0)
  • 2021-01-23 21:40

    Move the instantiation of the settings instance variable into your onCreate method. After the super.onCreate call.

    The way you are doing it now, it is getting set to null;

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