简体   繁体   English

如何使用sharedpreference存储一组ArrayList值

[英]How to store a set of ArrayList values using sharedpreference

The code below retrieves multiple selected contacts and stores it in the form of ArrayList but once I close the application and open the selected contact list is removed ,so the data should be stored so that once I close and open the app the data remains until the data is removed. 下面的代码检索多个选定的联系人并将其以ArrayList的形式存储,但是一旦我关闭应用程序并打开选定的联系人列表,则将删除数据,因此应存储数据,以便一旦我关闭并打开应用程序,数据将一直保留到数据被删除。 Can anyone please help me to store the ArrayList values using shared preference . 谁能帮我使用共享首选项存储ArrayList值。

 private void chooseContact() {
    Intent intentContactPick = new Intent(MainActivity.this,ContactsPickerActivity.class);
    MainActivity.this.startActivityForResult(intentContactPick,CONTACT_PICK_REQUEST);
}

@Override
public void onActivityResult(int requestCode,int resultCode,Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CONTACT_PICK_REQUEST && resultCode == RESULT_OK){


        ArrayList<Contact> selectedContacts = data.getParcelableArrayListExtra("SelectedContacts");

        String display="";
        for(int i=0;i<selectedContacts.size();i++){

            display += (i+1)+". "+selectedContacts.get(i).toString()+"\n";

        }
        contactsDisplay.setText("Selected Contacts : \n\n"+display);

    }

}

} }

the below code is the ArrayList which holds the selected contact values. 下面的代码是ArrayList,其中包含选定的联系值。

 ArrayList<Contact> selectedContacts = data.getParcelableArrayListExtra("SelectedContacts");

You have different options. 您有不同的选择。

  • Use a service and run it on background so data will not lost on close. 使用服务并在后台运行它,以使数据在关闭时不会丢失。
  • Write the data to an object and save it as file and read the object when you need the data. 将数据写入对象并保存为文件,并在需要数据时读取对象。
  • Write object to shared preference. 将对象写入共享首选项。

Convert your array or object to Json with Gson library and store your data as String in json format. 使用Gson库将您的数组或对象转换为Json,并将数据以JSON格式存储为String。

Save; 救;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();

String json = gson.toJson(arrayList);

editor.putString(TAG, json);
editor.commit();

Read; 读;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);

use import java.lang.reflect.Type for avoiding errors. 使用import java.lang.reflect.Type可以避免错误。

See this. 看到这个。

Store 商店

public void storeData(Context context,List<Contact> offlineData){

        SharedPreferences preferences=context.getSharedPreferences("contact_prefs",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        Gson gson=new Gson();
        editor.putString("data",gson.toJson(offlineData));
        editor.apply();
    }

Read

 public List<Contact> getData(Context context){
        SharedPreferences preferences=context.getSharedPreferences("contact_prefs",Context.MODE_PRIVATE);
        Gson gson = new Gson();
        return gson.fromJson(preferences.getString("data",null), new TypeToken<List<Photo>>() {
        }.getType());

    }

Ranjith KP answer is great. Ranjith KP的答案很好。 dont forget to add dependecy: 不要忘记添加依赖:

compile 'com.google.code.gson:gson:2.8.0'

for the context u can pass ur activity (just use 'this' instead). 对于上下文,您可以通过您的活动(仅使用“ this”代替)。

TAG - thats just a string, add TAG-多数民众赞成在只是一个字符串,添加

String TAG = "tag";

on your activity's members. 在您活动的成员上。

To save a key value pair to the shared preferences : 要将键值对保存到共享首选项:

SharedPreferences sharedPreference = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
Editor editor = sharedPreference.edit();
editor.putString(key, value);
editor.apply();

context : Pass the calling context or Base Context or Application Context ( getContext() in Fragments or getBaseContext() in Activity) context:传递调用上下文或基础上下文或应用程序上下文(Fragment中的getContext()或Activity中的getBaseContext()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM