[Android] Stores array data to SharedPreferences, android Array

Source: Internet
Author: User

[Android] Stores array data to SharedPreferences, android Array
If you want array data (such as boolean [], int [], etc.) to SharedPreferences, We can first organize the array data into json data and store it in SharedPreferences, when reading the data, it is OK to parse the json data.

For example, I want to save the boolean [] array data:

public static void saveApkEnalbleArray(Context context,boolean[] booleanArray) {SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);JSONArray jsonArray = new JSONArray();for (boolean b : booleanArray) {jsonArray.put(b);}SharedPreferences.Editor editor = prefs.edit();editor.putString(APK_ENABLE_ARRAY,jsonArray.toString());editor.commit();}


Read data:

public static boolean[] getApkEnableArray(Context context,int arrayLength){SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);boolean[] resArray=new boolean[arrayLength]; Arrays.fill(resArray, true);try {    JSONArray jsonArray = new JSONArray(prefs.getString(APK_ENABLE_ARRAY, "[]"));    for (int i = 0; i < jsonArray.length(); i++) {    resArray[i] = jsonArray.getBoolean(i);    }} catch (Exception e) {    e.printStackTrace();}            return resArray;}


When saving some complex object arrays, gson can be used to process the conversion between json and object.





For the storage of sharedpreferences in Android, the source code is as follows:

Share. edit (). remove ("number" + arg2). remove ("name" + arg2). commit ();
Listitem. revome (arg2 );
ListItemAdapter. policydatasetchanged ();

Add these sentences to onItemClickListener.

Also, do not remember whether SimpleAdapter directly uses the rmove method. If so, you do not need to call yydatasetchanged ();

What should I do if SharedPreferences needs to save an array?

The method for saving simple arrays. This google can have! PutIntArray (int []) putStringArray (String [])
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.