Reputation: 51
When I launch my app it just crashes and gives me this error code.:
Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
This is my main activity:
package com.awplicity.testappshared;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void onClick(View v) {
switch(v.getId()) {
case R.id.nextAct:
editor.putString("mystring", "Hi");
editor.commit();
startActivity(new Intent("com.awplicity.testappshared.Main2Activity"));
break;
}
}
}
This is the second activity:
package com.awplicity.testappshared;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tv_main2);
setText();
}
public void setText() {
SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
tv.setText(sharedPreferences.getString("mystring", ""));
}
}
Upvotes: 4
Views: 7993
Reputation: 1006604
Generally speaking, you cannot call methods that you inherit from Activity
(or subclasses, like AppCompatActivity
) until inside of the onCreate()
method. Until then, things are not set up yet.
Hence, change:
SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
to:
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
and initialize those fields in onCreate()
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
Upvotes: 10