Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempt to invoke virtual method 'android.content.SharedPreferences' on a null object reference [duplicate]

Tags:

java

android

I am new to android and i have not yet found a solution to this. How do i call SharedPreferences from a method. Calling it from onCreate i have no problem, but from another method i get an error and the app crashes. This is my Main Activity code

public class MainActivity extends BaseActivity {
  private SharedPreferences sharedPref;
  
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    sharedPref = getSharedPreferences(MY_PREFS,MODE_PRIVATE);

   }
   
   public String getUrl(){
    String url = sharedPref.getString("url", "(no url)");
    return url;
   }
}

This is the class intent to use my String value

public class AppConstant {
   static String url = new MainActivity().getUrl();

    public static String BASE_URL = url;
}

I am getting the error on the first line of shared preferences

Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

The method getUrl is not called from the activity but from another class, which is a non activity

like image 927
Dwayne T Avatar asked May 06 '26 13:05

Dwayne T


1 Answers

The best way would be to declare it as a global variable and use it where you need after initialize it in the onCreate:

public class MainActivity extends AppCompatActivity {
    private final String MY_PREFS = "myPrefs";
    private SharedPreferences sharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        sharedPref = this.getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);

    }

    public String getUrl(){
        String url = sharedPref.getString("url", "(no url)");
        return url;
    }

}
like image 52
Bogdan Android Avatar answered May 09 '26 02:05

Bogdan Android



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!