Closed maheshordex closed 6 years ago
You're calling set with null
The returned output of Converter.serialize
must not be null. Can you share your Converter implementation?
Please check below code it is correct or i missed something.
public static final String USER = "user";
public Preference<User> user;
public MyPrefs (Context context, Gson gson){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences (context);
rxPreferences = RxSharedPreferences.create (preferences);
user = rxPreferences.getObject(USER, new User (), new GsonAdapter<> (User.class));
}
public class GSONData{
public static Gson gson (){
Gson gson = new GsonBuilder ().serializeNulls ().create ();
return gson;
}
}
public class GsonAdapter<T> implements Preference.Converter<T>{
private Class<T> typeClass;
public GsonAdapter (Class<T> typeClass){
this.typeClass = typeClass;
}
@NonNull
@Override
public T deserialize (@NonNull String serialized){
return GSONData.gson ().fromJson (serialized, typeClass);
}
@NonNull
@Override
public String serialize (@NonNull T value){
return GSONData.gson ().toJson (value, typeClass);
}
}
I don't see a way that Gson.toJson returns null. If you can provide a failing example or test case, I can take a look.
Btw, I'd advise against making a new Gson instance every time you serialize. That requires creating a new TypeAdapter every time.
public final class GsonConverter<T> implements Preference.Converter<T> {
private final TypeAdapter<T> adapter;
public GsonAdapter(TypeAdapter<T> adapter) {
this.adapter = adapter;
}
@NonNull @Override public T deserialize (@NonNull String serialized) {
return adapter.fromJson(serialized);
}
@NonNull @Override public String serialize (@NonNull T value) {
return adapter.toJson(value);
}
}
rxPreferences.getObject(USER, DEFAULT_USER, new GsonConverter<>(gson.getAdapter(User.class)));
thanks for stepping in here @JakeWharton @NightlyNexus !
@maheshordex if you can provide a failing test case, that'd be the best way to get to the bottom of your issue.
@f2prateek @JakeWharton @NightlyNexus Thanks i got the issue.