1

I'm making an app where the user can enter their score and that will go into a list view. I want the strArr variable to save on exit so the score are still there when the user reopens the app. I've asked a question similar to this before where an int is saved however,I'm having a hard time doing the same with an ArrayList. Here's my code which currently crashes on launch.

public class AltonDuel extends Activity {

private Button bt;
private ListView lv;
private ArrayList<String> strArr;
private ArrayAdapter<String> adapter;
private EditText et;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alton_duel);
    bt = (Button) findViewById(R.id.button);
    lv = (ListView) findViewById(R.id.listView);
    et = (EditText) findViewById(R.id.editText);
    final Calendar cal = Calendar.getInstance();
    final int dd = cal.get(Calendar.DAY_OF_MONTH);
    final int mm = cal.get(Calendar.MONTH);
    final int yy = cal.get(Calendar.YEAR);

    int rideCountFile;

    final SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("AltonDuelCount", Context.MODE_PRIVATE);

    strArr = (ArrayList<String>) sharedPref.getStringSet("stringArr", new HashSet<String>());


    strArr = new ArrayList<String>();
    adapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, strArr);
    lv.setAdapter(adapter);
    bt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            strArr.add(dd + "-" + mm + "-" + yy + "    |     " + et.getText().toString());
            adapter.notifyDataSetChanged();

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putStringSet("stringArr", (Set<String>) strArr);
            editor.commit();

        }
    });
}}

Updated Code:

public class AltonDuel extends Activity {

private Button bt;
private ListView lv;
private ArrayList<String> strArr;
private ArrayAdapter<String> adapter;
private EditText et;
ArrayList<String> data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alton_duel);
    bt = (Button) findViewById(R.id.button);
    lv = (ListView) findViewById(R.id.listView);
    et = (EditText) findViewById(R.id.editText);
    final Calendar cal = Calendar.getInstance();
    final int dd = cal.get(Calendar.DAY_OF_MONTH);
    final int mm = cal.get(Calendar.MONTH);
    final int yy = cal.get(Calendar.YEAR);


    int rideCountFile;

    final SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("AltonDuelCount", Context.MODE_PRIVATE);

    data = (ArrayList<String>) sharedPref.getStringSet("stringArr", new HashSet<String>());
    Set<String> data = new HashSet<String>(strArr);

    strArr = new ArrayList<String>();
    adapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, strArr);
    lv.setAdapter(adapter);
    bt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            strArr.add(dd + "-" + mm + "-" + yy + "    |     " + et.getText().toString());
            adapter.notifyDataSetChanged();


            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putStringSet("stringArr", (Set<String>) strArr);
            editor.commit();

        }
    });
}}
Zak Woolley
  • 169
  • 2
  • 15
  • See [this answer](http://stackoverflow.com/a/23189535/4494555). This might help you – Jas Dec 31 '15 at 12:50
  • SharedPreferences are for storing small amounts of data. If you are storing larger data try to store in database. – user007 Dec 31 '15 at 12:51

2 Answers2

1

Here is my sample code for saving arraylist into sharedpreference

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mandaptak.android.Models.MatchesModel;
import com.mandaptak.android.Models.Participant;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Prefs {

  public static final String MANDAPTAK_SHARED_PREFERENCES_FILE = "mandapTak";

  public static String MATCHES = "matches";

  public static SharedPreferences getPrefs(Context context) {
    return context.getSharedPreferences(MANDAPTAK_SHARED_PREFERENCES_FILE, Context.MODE_MULTI_PROCESS);
  }


  public static ArrayList<MatchesModel> getMatches(Context context) {
    String json = getPrefs(context).getString(MATCHES, null);
    Type type = new TypeToken<ArrayList<MatchesModel>>() {
    }.getType();
    return new Gson().fromJson(json, type);
  }

  public static void setMatches(Context context, ArrayList<MatchesModel> list) {
    getPrefs(context).edit().putString(MATCHES, new Gson().toJson(list)).commit();
  }
}

here i am using getter and setter for storing and fetching array list from shared preference where MatchesModel is my custom model class containing properties to be store.

Rax
  • 1,347
  • 3
  • 20
  • 27
0

You're trying to cast an ArrayList to a Set. You can't do this. What you can do is create a new HashSet (or any implementation of Set) using your existing ArrayList. Like so:

When you want to retrieve data from the SharedPreferences:

Set<String> data = sharedPref.getStringSet("stringArr", new HashSet<String>());
ArrayList<String> myArrayList = new ArrayList<String>(data);

When you want to save data:

Set<String> data = new HashSet<String>(strAttr);
sharedPrefEditor.putStringSet("stringArr", data);
Tim Kranen
  • 4,202
  • 4
  • 26
  • 49
  • Thanks for the reply. So would that go where the data is being saved? – Zak Woolley Dec 31 '15 at 12:57
  • Get your shared preferences with the id: 'AltonDuelCount' and the get the string set out with the id: 'stringArr' – Tim Kranen Dec 31 '15 at 13:18
  • It crashes on launch. I've added the updated code to my initial answer – Zak Woolley Dec 31 '15 at 13:28
  • @ZakWoolley You're still casting a Set to an ArrayList, let me update my answer – Tim Kranen Dec 31 '15 at 13:32
  • I'm getting an error in the code. sharedPref.putStringSet is coming up red and it says can not resolve method. – Zak Woolley Dec 31 '15 at 13:39
  • Don't literally copy and paste my code, try to think for yourself. I don't have an editor right now so I can't test the code I put up. You of course need the Editor in order to put the string set in the shared pref. I've updated my answer. – Tim Kranen Dec 31 '15 at 13:41
  • I've managed to fix the error and it no longer crashes on launch but when I enter a value, exit the app and then go back into it, it doesn't show it in the list view. – Zak Woolley Dec 31 '15 at 13:54