Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Serializable Objects List into sharedPreferences

Tags:

android

Can anyone tell me how I can save a list of custom Serializable objects into SharedPreference? I am new To Android and I want to save an ArrayList<Contact> list into shared preferences.

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



}
like image 657
Usman Riaz Avatar asked Feb 05 '13 10:02

Usman Riaz


1 Answers

Another good solution is to use GSON. Here's an example:

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

More information about gson at http://code.google.com/p/google-gson/

Pretty simple right? ;)
Take care

like image 184
2 revs Avatar answered Sep 27 '22 20:09

2 revs