18

谁能告诉我如何将自定义 Serializable对象列表保存到中SharedPreference?我是 Android 新手,我想将一个保存ArrayList<Contact> list到共享首选项中。

public class MainActivity extends SherlockFragmentActivity {
PlaceSlidesFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;

public static final String TAG = "detailsFragment";

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main,
            container, false);

    mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
            .getSupportFragmentManager());

    mPager = (ViewPager) view.findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);

    mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
    ((CirclePageIndicator) mIndicator).setSnap(true);

    mIndicator
            .setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    Toast.makeText(MainActivity.this.getActivity(),
                            "Changed to page " + position,
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPageScrolled(int position,
                        float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
    return view;
    }



}
4

5 回答 5

33

另一个好的解决方案是使用 GSON。这是一个例子:

private static final String MAP = "map";    
private static final Type MAP_TYPE = new TypeToken<Map<MyObjA, MyObjB>>() {}.getType();

private static SharedPreferences prefs = MyApplication.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

private static Map<MyObjA, MyObjB> myMap;

public static void saveMap (Map<MyObjA, MyObjB> map) {
    SharedPreferences.Editor editor = prefs.edit();

    editor.putString(MAP, new Gson().toJson(map));
    editor.commit();
    myMap = map;
}

public static Map<MyObjA, MyObjB> loadMap() {
    if (myMap == null) {
        myMap = new Gson().fromJson(prefs.getString(MAP, null), MAP_TYPE);
    }
    return myMap;
}

有关 gson 的更多信息,请访问http://code.google.com/p/google-gson/

很简单吧?;)
保重

于 2013-05-17T11:31:59.147 回答
7

您可以使用JSON格式序列化您的ArrayList和它包含的对象,然后将String结果存储到SharedPreferences.

当您想取回数据时,检索字符串并使用 aJSONArray检索每个对象并将其添加到新的 ArrayList 中。

否则,您可以简单地使用Object(Input/Output)Stream类并使用(用于写入)将其写入不同的文件

FileOutputStream fos = this.openFileOutput(fileName, MODE_PRIVATE);
final OutputStreamWriter osw = new OutputStreamWriter(fos);
JSONArray array = new JSONArray();

// Add your objects to the array

osw.write(array.toString());
osw.flush();
osw.close();
于 2013-02-05T11:15:37.040 回答
3

最简单的出路?

转换JSON并保存为String.

于 2013-02-05T11:10:33.990 回答
1

如果它已经序列化,那么你可以把它放进去。这篇文章中接受的答案将为你指明方向:将 ArrayList 保存到 SharedPreferences

于 2013-02-05T11:01:45.900 回答
0

试试这个,对我有用:

implementation 'com.google.code.gson:gson:2.7'

数据列表.java:

import java.util.List;

public class DataList {
    List<Data> dataList;

    public List<Data> getDataList() {
        return dataList;
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }
}

MainActivity.java :

    List<Data> fetchLog = new ArrayList<Data>();
    DataList dataList = null;


    dataList = new DataList();
    Gson gson = new Gson();

    //SAVE List As SharedPreferences
    Data data = new Data("ali",20);
    fetchLog.add(data);
    dataList.setDataList(fetchLog);
    Gson gson = new Gson();
    String json = gson.toJson(dataList);
    
    utils.setPref("logs", json);// function to set SharedPreferences


    // read List from SharedPreferences
        String json = utils.getPref("logs");// function to read SharedPreferences
        if (! json.equals("")) {
            dataList = gson.fromJson(json, DataList.class);
            fetchLog = dataList.getDataList();
        }
于 2020-09-12T10:29:27.337 回答