[java] java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

I am trying to save player's name in shared preference and make it display in another activity by getting it again in shared preference but my app crash.

FATAL EXCEPTION: main

 Process: plp.cs4b.thesis.drawitapp, PID: 1970
 java.lang.RuntimeException: Unable to start activity ComponentInfo{plp.cs4b.thesis.drawitapp/plp.cs4b.thesis.drawitapp.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
    at plp.cs4b.thesis.drawitapp.PlayGame.onCreate(PlayGame.java:20)
    at android.app.Activity.performCreate(Activity.java:5933)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
    ... 10 more

Codes:

Player.java

public class Player {

private Context context;
private SharedPreferences prefSettingsU;
private SharedPreferences.Editor prefEditorU;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static final String MY_UNIQUE_PREF_FILE = "DrawItApp";

public Player(Context context, String name) {
    this.context = context;
    saveName(name);
}

public void saveName(String n) {
    prefSettingsU = context.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
    prefEditorU = prefSettingsU.edit();
    prefEditorU.putString("keyName", n);
    prefEditorU.commit();
}

public String getName(Context ctx) {
    prefSettingsU = ctx.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
    String name = prefSettingsU.getString("keyName", "ANONYMOUS");
    return name;
}

PlayGame.java

public class PlayGame extends Activity {

private TextView welcomePlayer;
private ListView createdGames;
private Player mPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.play_game);

    welcomePlayer = (TextView) findViewById (R.id.tvPlayerName);
    welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

    createdGames = (ListView) findViewById (R.id.listCreatedGames);
    // adapter etc
    createdGames.setEmptyView(findViewById (R.id.tvNoGames));


}

PlayerName.java

public class PlayerName extends Activity {

private EditText playerName;
private Player mPlayer;
public static Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player_name);
    context = this;
    playerName = (EditText) findViewById (R.id.etName);

}

public void onC_Confirm(View btnclick) {
    mPlayer = new Player(context, String.valueOf(playerName.getText()));
    //mPlayer.saveName();
    Intent intent = new Intent(PlayerName.this, PlayGame.class);
    startActivity(intent);
}

public void onC_testShPref(View btnclick) {
    Intent intent = new Intent(PlayerName.this, PlayGame.class);
    startActivity(intent);
}

This question is related to java android nullpointerexception

The answer is


Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to nullpointerexception

Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Null pointer Exception on .setOnClickListener - java.lang.NullPointerException - setText on null object reference NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Java 8 NullPointerException in Collectors.toMap NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0