how to show data from a sharedPreferences in a ListActivity

1

I'm starting to work with SharedPreferences on android, a simple and fast way to store static and primitive data. However, my problem is in showing these saved values in a ListActivity. I have already searched here in the forum, google tutorials, but no method worked. If anyone can help me thank you then I must deliver this work this week.

    
asked by anonymous 02.03.2016 / 15:59

3 answers

1

To get all saved values use the getAll () of SharedPreferences:

Map<String,?> map = prefs.getAll();

For a list of values use:

List<Value> list = new ArrayList<Value>(map.values());

Use the list to build the ListView as usual.

If you want to get the Keys list use:

List<Value> list = new ArrayList<Value>(map.keys());

Android provides api Preferences to program a user interface type of "system settings" .
Instead of using View objects to create the user interface, the settings are created through various subclasses of the class Preference declared in an XML file.

To display the preference list, a PreferenceActivity ( API

02.03.2016 / 16:26
0

Placing values:

public static final String PREFS = "MinhaPreferencia";
SharedPreferences.Editor editor = getSharedPreferences(PREFS, MODE_PRIVATE).edit();
editor.putString("nomeUsuario", "Marllon Nasser");
editor.putInt("idUsuario", 10);
editor.commit();

Getting values:

SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE); 
String textoArmazenado = prefs.getString("text", null);
if (textoArmazenado != null) {
   String nomeUsuario= prefs.getString("nomeUsuario", "Nenhum nome definido");//"Nenhum nome definido" é o valor "default"
   int idUsuario = prefs.getInt("idUsuario", 0); //0 é o valor "default"
}

More information here and here

    
02.03.2016 / 16:04
0

Here is an example of how to get a Set<String> :

  // Pegamos a lista do SharedPreferences
        Set<String> itens = sharedPreferences.getStringSet(ITENS_LISTA, null);
        if(null == itens){
            // Se for nula, vamos popular..
            itens = new HashSet<>(0);
            int pt = 1;
            while(pt < 10){
                itens.add("Item "+pt);
                pt++;
            }
            // Editor , para atualizar a lista
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putStringSet(ITENS_LISTA, itens);
        }


        // criamos uma lista de String
        String[] valores = new String[itens.size()];
        int pt=0;
        for(String item : itens){
            valores[pt] = item;
            pt++;
        }

        // Instancia do ArrayAdapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,  android.R.layout.simple_list_item_1, valores);
    
02.03.2016 / 16:46