Search code examples
androidandroid-preferencespreferenceactivityandroid-sharedpreferences

NullPointerException with SharedPreferences


my logical I am trying to get a textView from my Main.java file, and when the notification is clicked, it should print it. I know I am to use sharedPreferences for that. I did that. However, it keeps throwing a NullPointerException, but I have called everything i need to call in my NotificationPage.java class so I am not sure what exactly is wrong. Please any help is appreciated.

This is my NotificationPage.java class

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;


public class NotificationPage extends Activity {
SharedPreferences sp;
SharedPreferences.Editor edit;
TextView arrival;
TextView notifdate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.notification);
    notifdate=(TextView)findViewById(R.id.textView5);
    arrival=(TextView)findViewById(R.id.textView4);
    sp=getSharedPreferences(arr, MODE_PRIVATE);
    edit=sp.edit();
    sp.getString(arr, null);
    edit=sp.edit();
    edit.putString(arr,sp.getString(arr,null));
    notifdate.setText("Hey!" + sp.getString(arr,null));
    edit.apply();
}

this is the line of code that gets my shared preferences from my other java file

arr=arrival.getText().toString();
sp=getSharedPreferences(arr,MODE_PRIVATE);

Solution

  • Put a key-value

    public static final String SP_NAME = "my_preferences";
    SharedPreferences sp = getSharedPreferences(SP_NAME, MODE_PRIVATE);
    sp.edit().putString("key", "value").apply();
    

    Get a value

    SharedPreferences sp = getSharedPreferences(SP_FILE_NAME, MODE_PRIVATE);
    String value = sp.getString("key", "defaultValue");