James
James

Reputation: 129

Getting shared preferences and displaying them in a listview

So I have some shared preferences in my main activity:

SharedPreferences prefs = this.getSharedPreferences("myFavs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

And I add some generated strings as a key value pair:

editor.putString(saved,saved);
editor.apply();

In another activity I would like to be able to display all the key value pairs I have saved in my shared preferences file into a ListView.

I have used things like:

 ListView listView = (ListView) findViewById(R.id.favsList);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listlayout, android.R.id.text1, values );
    listView.setAdapter(adapter);

before, however I am not sure how to get all my shared preferences into a format that I can put into a ListView.

P.S I should have mentioned I only really need a list of either keys or values as the key and the value are always the same.

I think this might have solved my problem:

SharedPreferences prefs = getSharedPreferences("myFavs", 0);
    Map<String, String> m = (Map<String, String>) prefs.getAll();
    List<String> list = new ArrayList<>(m.values());

Is this correct?

Upvotes: 1

Views: 2291

Answers (1)

droidev
droidev

Reputation: 7380

if I understood in correct sense, what you need is to retrieve all preference values.

for that you can use this ;

 Map<String,?> allPrefs = prefs.getAll();      
    for(Map.Entry<String,?> entry : allPrefs.entrySet()){
      String key = entry.getKey();
      String value = entry.getValue().toString();
     }

you can store the values to an array and use.

UPDATE

more precisely

    public String[] fetchAllPreference(){
     String[] values = new String();
     int index = 0;
     Map<String,?> allPrefs = prefs.getAll();      

     for(Map.Entry<String,?> entry : allPrefs.entrySet()){
       value[index++] = entry.getValue().toString();
     }
     return values; 
    }

you can use this function for getting all the preference and the returned String array you can provide to your Listview adapter

Upvotes: 2

Related Questions