Search code examples
javaandroidsharedpreferencesandroid-arrayadapternavigation-drawer

Store and retrieve strings in ArrayAdapter with SharedPreferences


I need to save and retrieve two strings in an ArrayAdapter of my NavigationDrawer. First of all. I declared this:

private static SharedPreferences prefs;

then in the getView() method

SharedPreferences.Editor editor = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE).edit();
        editor.putString("username", NameStr);
        editor.putString("photo", urlProfile);
        editor.commit();

In this way i'm going to save the strings i need. But i'm not exactly sure because i never use the Sharedpreferences in an Adapter. How can i retrieve the datas? Where have i to put it? thanks

EDIT: to achieve the strings i wrote in getView()

Intent intent = ((Activity) context).getIntent();
            NameStr = intent.getStringExtra("username");
            urlProfile = intent.getStringExtra("photo");

where the two strings comes from another activity.

EDIT2: SOLUTION Dexter got the solution and it works perfectly:

  SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS",context. MODE_PRIVATE);
        if(sharedPreferences == null) return;        
        NameStr = sharedPreferences.getString("username", "");
        urlProfile = sharedPreferences.getString("photo", "");
        SharedPreferences.Editor editor = sharedPreferences.edit();        
        Intent intent = ((Activity) context).getIntent();
        if(NameStr == null || NameStr.equals("")) {
            NameStr = intent.getStringExtra("username");
            editor.putString("username", NameStr);
        }
        if(urlProfile == null || urlProfile.equals("")) {
            urlProfile = intent.getStringExtra("photo");
            editor.putString("photo", urlProfile);
        }
        editor.apply();

all of this in the Adapter construction!


Solution

  • You can retrieve the data using :

    SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE);
    String username = sharedPreferences.getString("username", "");
    String photo = sharedPreferences.getString("photo", "");
    

    Also prefer using editor.apply()