Vichit Vichit - 1 year ago 63
Android Question

Android - I try to get data from SharePreference

Here is my code that I try to insert data to share Preference when I click on Item.

@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_Favorite:
songList = songRespones.getSongs();

SharedPreferences sharedPreferences = getContext().getSharedPreferences(
SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();

String songJson = new Gson().toJson(songList.get(position));

editor.putString(SharePreferenceKey.SONG_LIST, songJson);
editor.apply();

showMessage("អ្នកបានរក្សាទុក");

break;
case R.id.popup_cencel:
showMessage("Cancel");
break;
}
return false;
}
});


Here is my code that I want to get data from Share Preference

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

SharedPreferences sharedPreferences = getContext().getSharedPreferences(
SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);

String getSongJson = sharedPreferences.getString(SharePreferenceKey.SONG_LIST, "N/A");

List<SongRespones> songList;
if (!getSongJson.equals("N/A")) {
Type type = new TypeToken<List<SongRespones>>(){}.getType();
songList = new Gson().fromJson(getSongJson, type);
Log.e("ppppp", songList.size() + "");
}
}


But I cannot get it. It show Error below:

FATAL EXCEPTION: main Process: com.vichit.khmersong, PID: 20040

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.Gson.fromJson(Gson.java:899)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.google.gson.Gson.fromJson(Gson.java:801)


Please help me:

Answer Source

You are storing a json object because songList.get(position) will return an object so

Change this line

 String songJson = new Gson().toJson(songList.get(position));

to this

 String songJson = new Gson().toJson(songList);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download