I have an android application, and in it I save some basic user information in SharedPreferences, however I started to display the following JSON parse error:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $
Codes:
Class for Handling SharedPreferences:
public static void setPreferences(Context ctx, String key, Object value) {
pref = ctx.getSharedPreferences(arquivo, 0);
editor = pref.edit();
key = key.toLowerCase();
if (key == null || value == null) {
return;
}
Gson gson = new Gson();
String json = gson.toJson(value);
editor.putString(key, json);
editor.commit();
}
public static String getPreferences(Context ctx, String key) {
pref = ctx.getSharedPreferences(arquivo, 0);
String obj = pref.getString(key, "");
return obj;
}
Save Something Code:
Note: I convert everything to Object before saving.
Gson gson = new Gson();
//Recupero o Objeto para editar o que tem gravado
String aux = SharedPreferences.getPreferences(ctx, "configuracao");
Configuracao c = gson.fromJson(aux, Configuracao.class);
//Salvo Novamente
SharedPreferences.setPreferences(ctx, "configuracao", c);
The first time I save, it works fine, however when I try to get it from SharedPreferences it throws the exception above when casting:
SharedPreferences.setPreferences(ctx, "configuracao", c);
Configuration Class
public class Configuracao {
private String ip;
private String porta;
private String caminhoWebService;
public Configuracao(){
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPorta() {
return porta;
}
public void setPorta(String porta) {
this.porta = porta;
}
public String getCaminhoWebService() {
return caminhoWebService;
}
public void setCaminhoWebService(String caminhoWebService) {
this.caminhoWebService = caminhoWebService;
}
}
The first time I save the configuration object and call getPreferences then the object comes like this: // It works
{"caminhoWebService":"http://192.168.254.8:8084/UltraMensagensREST/recursos"}
If I make a set again, replacing what was written, and call a get again, comes this in return: // throws the exception
"{\"caminhoWebService\":\"http://192.168.254.8:8084/UltraMensagensREST/recursos\"}"
In this case, throw the exception above.
Does anyone know what it can be?