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();

        }
    });
}}
2
  • See this answer. This might help you Commented Dec 31, 2015 at 12:50
  • SharedPreferences are for storing small amounts of data. If you are storing larger data try to store in database. Commented Dec 31, 2015 at 12:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

7 Comments

Thanks for the reply. So would that go where the data is being saved?
Get your shared preferences with the id: 'AltonDuelCount' and the get the string set out with the id: 'stringArr'
It crashes on launch. I've added the updated code to my initial answer
@ZakWoolley You're still casting a Set to an ArrayList, let me update my answer
I'm getting an error in the code. sharedPref.putStringSet is coming up red and it says can not resolve method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.