title: Shared Preferences on a Null Object Reference Android
body: <p>I am new to android developing maybe its a silly question but please help me. I am getting this error while trying to save an int value.</p>
  
  <blockquote>
    <p>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference</p>
  </blockquote>
  
  <p>And here is my code</p>
  
  <pre><code>SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
  String value = "com.example.app.value";
  int i = prefs.getInt(value, 0);
  </code></pre>
  
  <p>And for write </p>
  
  <pre><code>prefs.edit().putInt(number, i).apply();
  </code></pre>
  
  <p>I just want to set a SharedPreferences and want to read it at the first and write it inside the Activity. How can I solve it?</p>
  
  <p>EDIT</p>
  
  <pre><code>public class MainActivity extends Activity {
  SharedPreferences sharedpreferences;
  public static final String MyPREFERENCES = "myprefs";
  public static final  String value = "key";
  
  int i = sharedpreferences.getInt(value, 0);
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
  }
  public void sendMessage(View view) {
      i += 1;    
      SharedPreferences.Editor editor = sharedpreferences.edit();
      editor.putInt(value, i);
      editor.apply();
  }
  </code></pre>
  
  <p>I managed to save preferences with a different way but I couldn't manage to read it in MainActivity extends Activity class.</p>
  
  <p>log :</p>
  
  <blockquote>
    <p>Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference</p>
  </blockquote>