2013-02-05 99 views
17

誰能告訴我如何將自定義的Serializable對象列表保存到SharedPreference?我是Android新手,我想將ArrayList<Contact> list保存到共享偏好設置中。將可序列化的對象列表保存到sharedPreferences中

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



} 

回答

7

可以使用JSON格式序列化您的ArrayList和對象包含,然後String結果存儲到SharedPreferences

當您想要取回數據時,請檢索字符串並使用JSONArray來檢索每個對象並將其添加到新的ArrayList。

否則,你可以簡單地使用Object(Input/Output)Stream類,並用它編寫成differente文件(寫)

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(); 
+1

thanks iT wORKS –

3

最簡單的辦法呢?

轉換爲JSON並將其另存爲String

33

另外一個很好的解決方案是使用GSON。這裏有一個例子:在http://code.google.com/p/google-gson/

很簡單說得對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; 
} 

的更多信息? ;)
小心