Simple string array to preferences and into ListView

Based on a combination of these stackoverflow links (ArrayList into prefs and arrayList into ListView).

Create ArrayList and save to preferences.

SharedPreferences prefs = null;
ArrayList logs;
prefs = PreferenceManager.getDefaultSharedPreferences(this);

	logs = new ArrayList();
	logs.add("aaaaaaaa");
	logs.add("bbbbbbbb");
	logs.add("cccccccc");
	SharedPreferences.Editor editor = prefs.edit();
	editor.putInt("log_size", logs.size());
	for(int i=0;i<logs.size();i++)  
        {
	  editor.remove("log" + i);
	  editor.putString("log" + i, logs.get(i));  
         }
	editor.commit();

Read from preferences.

logs.clear();
int size = prefs.getInt("log_size", 0);  
    for(int i=0;i<size;i++) 
     {
      logs.add(prefs.getString("log" + i, null));
     }

Into simple ListView.

ListView lv = (ListView) findViewById(R.id.listView1);
ArrayAdapter arrayAdapter =      
         new ArrayAdapter(this,android.R.layout.simple_list_item_1, logs);
         lv.setAdapter(arrayAdapter);

 

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *