使用JSON对象获取Model类的Arraylist

时间:2014-05-25 13:14:21

标签: android json arraylist

我试图将Model类的arraylist放入JSON对象,最后放入共享首选项。但是当从JSON对象检索值到ArrayList类时,我得到一个错误java.lang.string无法强制转换为java.util.Arraylist。我的主要目标是添加再次打开Activity时可见的播放列表。如果还有其他任何方法可以比这更容易,建议也是最受欢迎的。在我的代码下方粘贴:

 private void saveData(ArrayList<PlaylistModel> play) {
    JSONObject ob = new JSONObject();
    try {
        ob.put("items", play);
    } catch (JSONException e) {

        e.printStackTrace();
    }
    data.put(ob);
    playAdapter = new PlaylistAdapter(CreatePlaylist.this, playlist);
    list.setAdapter(playAdapter);

    SharedPreferences preferences = getSharedPreferences("application", 0);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("playlist_data", data.toString());
    editor.commit();

}
//Retreiving value 
SharedPreferences pref = getSharedPreferences("application", 0);
    try {
        if (pref.getString("playlist_data", null) != null) {
                            data = new JSONArray(pref.getString("playlist_data", null));
        }
    } catch (JSONException e) {

        e.printStackTrace();
    }
if (data != null && data.length() > 0) {

        for (int i = 0; i < data.length(); i++) {
            JSONObject ob = null, ob1 = null;
            try {
                ob = (JSONObject) data.get(i);

                Object obj = ob.get("items");
                Log.d("JSON obj value1", "" + obj);
                       retrievedPlaylist = (ArrayList<PlaylistModel>) obj; //error here
                playAdapter = new PlaylistAdapter(CreatePlaylist.this,
                        retrievedPlaylist);
                list.setAdapter(playAdapter);


            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

    }

1 个答案:

答案 0 :(得分:0)

private void saveTextViewData(String playlistName, int tracks) {
    JSONObject ob = new JSONObject();
    try {
        ob.put("playlistName", playlistName);
        ob.put("noOfTracks", tracks);
    } catch (JSONException e) {

        e.printStackTrace();
    }
    data.put(ob);
    playAdapter = new PlaylistAdapter(CreatePlaylist.this, playlist);
    list.setAdapter(playAdapter);

    SharedPreferences preferences = getSharedPreferences("application", 0);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("playlist_data", data.toString());

    editor.putLong("playlistid", playlistId);
    Log.d("inside savetextview=", data.toString());
    editor.commit();

}

    for (int i = 0; i < data.length(); i++) {
            JSONObject ob = null;
            try {
                ob = data.getJSONObject(i);

            } catch (JSONException e) {

                e.printStackTrace();
            }

            PlaylistModel model = PlaylistModel.fromJson(ob);//used dis
}