Search code examples
androidsharedpreferences

How to get values from shared preferences for class by another class


I want to get a string from my shared preference file and use for more classes, but I don't know why not work. My reader class is:

import android.app.Activity;
import android.content.SharedPreferences;

public class A {
    public static String url2;

    public void execute() {

        String URLPref = "URL";
        SharedPreferences prefs = getSharedPreferences("com.exam.search_preferences",Activity.MODE_PRIVATE);
        url2 = prefs.getString(URLPref , "");

    }

    private SharedPreferences getSharedPreferences(String string,
            int modePrivate) {

        return null;
    }


}

And the second class that uses the string

public class SearchHome extends Activity {

    static String url2;
    A cls2= new A();

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

        cls2.execute();
        url2 = A.url2;


        Toast.makeText(getApplicationContext(),"URL:" + url2 ,
        Toast.LENGTH_LONG).show();
...

Sorry for my bad english, I never learned.But I'm trying!


Solution

  • You need to pass the Context to your class A, because you can get the SharedPreferences from a Context object. NOTE, an Activity is a Context to some extend

    public class A {
        public static String url2;
    
        /** @param context used to get the SharedPreferences */
        public void execute(Context context) {
    
            String URLPref = "URL";
            SharedPreferences prefs = context.getSharedPreferences("com.exam.search_preferences",Activity.MODE_PRIVATE);
            url2 = prefs.getString(URLPref , "");
        }
    }
    

    And then pass the Context to your execute method

    public class SearchHome extends Activity {
    
        static String url2;
        A cls2= new A();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.search_activity);
    
            // pass context 'this' to the execute function
            // This works, because SearchHome extends Activity 
            cls2.execute(this);
            url2 = A.url2;
            ...