インタフェース, impl, Factory実装

This commit is contained in:
ろむねこ 2024-06-12 14:44:26 +09:00
parent f87d59672d
commit bcf3503868
Signed by: Fujimatsu
GPG Key ID: FA1F39A1BA37D168
3 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package one.nem.kidshift.utils;
import android.content.SharedPreferences;
import java.util.List;
public interface SharedPrefUtils {
// Single
<T> String saveObject(String key, T object);
<T> String saveObject(T object); // auto generate key
<T> T getObject(String key, Class<T> clazz);
// Common
void reset();
void remove(String key);
}

View File

@ -0,0 +1,9 @@
package one.nem.kidshift.utils.factory;
import dagger.assisted.AssistedFactory;
import one.nem.kidshift.utils.impl.SharedPrefUtilsImpl;
@AssistedFactory
public interface SharedPrefUtilsFactory {
SharedPrefUtilsImpl create(String name);
}

View File

@ -0,0 +1,64 @@
package one.nem.kidshift.utils.impl;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import java.util.List;
import dagger.assisted.Assisted;
import dagger.assisted.AssistedInject;
import dagger.hilt.android.qualifiers.ApplicationContext;
import one.nem.kidshift.utils.SharedPrefUtils;
public class SharedPrefUtilsImpl implements SharedPrefUtils {
private final Context applicationContext;
private final String name;
private final Gson gson;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@AssistedInject
public SharedPrefUtilsImpl(@ApplicationContext Context applicationContext, @Assisted String name) {
this.applicationContext = applicationContext;
this.name = name;
this.gson = new Gson();
// Get the shared preferences
sharedPreferences = applicationContext.getSharedPreferences(name, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
@Override
public <T> String saveObject(String key, T object) {
String json = gson.toJson(object);
editor.putString(key, json).apply();
return key;
}
@Override
public <T> String saveObject(T object) {
String key = String.valueOf(sharedPreferences.getAll().size());
return saveObject(key, object);
}
@Override
public <T> T getObject(String key, Class<T> clazz) {
String json = sharedPreferences.getString(key, null);
return gson.fromJson(json, clazz);
}
@Override
public void reset() {
editor.clear().apply();
}
@Override
public void remove(String key) {
editor.remove(key).apply();
}
}