Skip to content

Instantly share code, notes, and snippets.

@Ankit-Slnk
Created July 17, 2021 05:22
Show Gist options
  • Save Ankit-Slnk/80eed01907620acde87270c6fb4336a7 to your computer and use it in GitHub Desktop.
Save Ankit-Slnk/80eed01907620acde87270c6fb4336a7 to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
public class ComplexPreferences {
private static ComplexPreferences complexPreferences;
private Context context;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
private ComplexPreferences(Context context, String namePreferences, int mode) {
this.context = context;
if (namePreferences == null || namePreferences.equals("")) {
namePreferences = "complex_preferences";
}
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
}
public static ComplexPreferences getComplexPreferences(Context context, String namePreferences, int mode) {
if (complexPreferences == null) {
complexPreferences = new ComplexPreferences(context, namePreferences, mode);
}
return complexPreferences;
}
public void putObject(String key, Object object) {
if (object == null) {
throw new IllegalArgumentException("object is null");
}
if (key.equals("") || key == null) {
throw new IllegalArgumentException("key is empty or null");
}
editor.putString(key, GSON.toJson(object));
}
public void commit() {
editor.commit();
}
public <T> T getObject(String key, Class<T> a) {
String gson = preferences.getString(key, null);
if (gson == null) {
return null;
} else {
try {
return GSON.fromJson(gson, a);
} catch (Exception e) {
throw new IllegalArgumentException("Object storaged with key " + key + " is instanceof other class");
}
}
}
}
import android.content.Context;
import android.content.Intent;
public class PrefUtils {
public static UserResponse getUser(Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "appUser", 0);
UserResponse currentUser = complexPreferences.getObject("loggedinUser", UserResponse.class);
return currentUser;
}
public static void setUser(UserResponse currentUser, Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "appUser", 0);
complexPreferences.putObject("loggedinUser", currentUser);
complexPreferences.commit();
}
public static void signOut(Context ctx) {
setUser(new UserResponse(), ctx);
Intent i = new Intent(ctx, LoginActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
ctx.startActivity(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment