为什么我的SharedPreferences不起作用? - 检索到的Object为null

时间:2015-08-10 15:48:23

标签: java android json gson sharedpreferences

我正在尝试保存ColorBean类的对象,当应用转到onStop()

public class MainActivity extends ExpandableListActivity {

    private ColorAdapter expListAdapter;
        LinkedHashMap<String, ArrayList<ColorBean>> colorsMap2 = new LinkedHashMap<String, ArrayList<ColorBean>>();
        SharedPreferences prefs;
        static String fileName = "SharedObject";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            ArrayList<String> groupNames = new ArrayList<String>();

            prefs = getPreferences(MODE_PRIVATE);
            final LinkedHashMap<String, ArrayList<ColorBean>> colorsMap = new LinkedHashMap<String, ArrayList<ColorBean>>();

            ArrayList<ColorBean> color = new ArrayList<ColorBean>();
            //Trying to fetch the prefs
            colorsMap2 = (LinkedHashMap<String, ArrayList<ColorBean>>) loadFromSharedPrefs();

            if (colorsMap2 == null || colorsMap2.size() == 0)
                Toast.makeText(this, "Not Retrieved", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onResume() {
            super.onResume();
            //fetching them here too
            if (loadFromSharedPrefs() != null) {
                colorsMap2 = (LinkedHashMap<String, ArrayList<ColorBean>>) loadFromSharedPrefs();
            }
        }

        @Override
        protected void onStop() {
            super.onStop();
            //saving the preferences
            saveToSharedPrefs(colorsMap2);
        }

        public void saveToSharedPrefs(Object objToSave) {
            SharedPreferences.Editor editor = prefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(objToSave);
            editor.putString("MyObject", json);
            editor.commit();
        }

        public Object loadFromSharedPrefs() {
            Toast.makeText(this, "loading", Toast.LENGTH_SHORT).show();
            Gson gson = new Gson();
            Object obj = null;
            if (prefs != null) {
                String json = prefs.getString("MyObject", "");
                obj = gson.fromJson(json, Object.class);
            }
            return obj;
        }
    }

1 个答案:

答案 0 :(得分:0)

看起来您需要更改一行:

obj = gson.fromJson(json, Object.class);

为:

obj = gson.fromJson(json, LinkedHashMap<String, ArrayList<ColorBean>>.class);

<强>已更新

对不起,自从我使用Gson以来已经有一段时间了,是的,你是对的,我上面所说的将不起作用。序列化类型时需要存储泛型类型信息,因此在序列化和反序列化时需要使用Gson的TypeToken类:

Type mapType = new TypeToken<LinkedHashMap<String, ArrayList<ColorBean>>>(){}.getType();

然后使用:

序列化
String json = gson.toJson(objToSave, mapType);

并使用:

反序列化
obj = gson.fromJson(json, mapType);

有一个教程here涵盖了使用Gson和泛型类型。