2

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

Dwayne T
  • 95
  • 2
  • 8

1 Answers1

1

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;
    }

}
Bogdan Android
  • 1,345
  • 2
  • 10
  • 21
  • still getting same error on this line String url = sharedPref.getString("url", "(no url)"); – Dwayne T Nov 11 '20 at 08:35
  • Can you post your full code to know where are you using it? looks strange, but I am sure it's an easy error. – Bogdan Android Nov 11 '20 at 08:38
  • i wanted to but someone closed my question, sadly – Dwayne T Nov 11 '20 at 08:49
  • Damn... Ok I have checked your edit, you are not using it correctly, you shouldn't do a new from an Activity, it's not a regular class, If you use my answer (note the MY_PREFS value), you could get the sharedPreferences object and use it across this activity. To get the sharedPreferences you always need a context. – Bogdan Android Nov 11 '20 at 09:18
  • now i am left with one problem of overriding that static value. It has to change whenever i click a different button, if i try to make it non static i get an error of cannot have a non static variable from a static context – Dwayne T Nov 11 '20 at 09:49