1

I've been trying to save an integer array list in shared preferences for a couple of days now but cannot figure out how to do it.

here's the array list i'm trying to save

        ////list that contains checked routes///
        ArrayList<Integer> checkedRoutePosition = new ArrayList<>();

and here's how the array obtains the values within it

       int listViewItemPosition = ((Activity) getContext()).getIntent().getIntExtra("listViewItemPosition",0);

       checkedRoutePosition.add(listViewItemPosition);

In another activity after you click the back button a new intent is started that takes me to this activity. The intent passes in the listViewItemPosition value that I need to save to the array.

The above lines of code are in my getView method of my custom adapter for a listview. After saving them I want to compare them to position in my getView. Where the values are equal I want to set a certain image. Is this code the right way to do that?

  for(int i=0; i<checkedRoutePosition.size(); i++)
                if(position == checkedRoutePosition.get(i)) {
                    checkImageView.setImageResource(checkImageResourceId);
                }

Thanks for any help!

1 Answer 1

2

You can't write any arrays or arraylists to shared preferences. The closest you can do is write the integers to a comma separated string, write the string, and parse it when you need to read it. This is only appropriate if the size of the array is relatively small. If its large, you need to move away from SharedPreferences to another form of storage such as a file or database.

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

3 Comments

It will have about 180 values in it. Is that too large?
THe main effect of it being too large will be it being slow to parse and slow to read/write the shared preference, especially if there's other data in the same preference file. So too big is mainly determined by performance.
Using a sql database would be a better solution

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.