user3542379
user3542379

Reputation: 21

How to save dynamically added items in Listview with sharedpreferences?

        protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    preferences = getSharedPreferences(FAVORI, 0);

    ListView favlist = (ListView) findViewById(R.id.favoriliste);

    ArrayList<String> foo = new ArrayList<String>();
    String [] bar = foo.toArray(new String[0]);

    public void favekle(String string) {

    foo.add(string);
    bar = foo.toArray(new String[0]);

    favadapter = new MyFavAdapter(Diziler.this,
            android.R.layout.simple_list_item_1, R.id.txtTitle, bar);
    // favlist= new ArrayList<>();
    favlist.setAdapter(favadapter);
    favadapter.notifyDataSetChanged();

}       
    favadapter = new MyFavAdapter(Diziler.this,
            android.R.layout.simple_list_item_1, R.id.txtTitle, bar);
    // favlist= new ArrayList<>();
    favlist.setAdapter(favadapter);
    favadapter.notifyDataSetChanged();

Hello.I need help.I want save dynamically added items in Listview with SharedPreferences. I'm adding listview items with public void favekle function.I'm adding items to ArrayList<> than i convert ArrayList<> to string array finally i set items to adapter. If i restart application my listview items disappear. How can i save added items with sharedpreferences?I used StringBuilder but it didn't work.Thank you.

Upvotes: 0

Views: 1635

Answers (3)

ashishduh
ashishduh

Reputation: 6699

You can store string sets in Shared Preferences, then convert them back to a List when you retrieve them.

ArrayList<String> list = new ArrayList<String>();
list.add("test1");
list.add("test2");

PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("stringset", new HashSet<String>(list))
    .commit();

Upvotes: 0

ILovemyPoncho
ILovemyPoncho

Reputation: 2792

You are supposed to store single key-value paired data with SharedPreferences. Trying to store big grouped data is not efficient at all. You should use an SQLite database.

SQLite and ContentProvider Tutorial

Upvotes: 0

Suhas K
Suhas K

Reputation: 74

You can save to shared preference in this way

SharedPreferences sp = context.getSharedPreferences(
            "file name", 0);
    SharedPreferences.Editor spEdit = sp.edit();
    spEdit.putLong(key, value);
    spEdit.commit();

Upvotes: 0

Related Questions