There is a DataStoreManager class that is used to create an DataStore Preferences file in Android app as this is an alternative of the deprecated SharedPreferences.
public class DataStoreManager {
public static final DataStoreManager instance = new DataStoreManager();
private static final Handler dataStoreManagerHandler = new Handler(Looper.getMainLooper());
private DataStoreManager() {
}
private RxDataStore<Preferences> dataStore;
public void init(Context context) {
dataStore = new RxPreferenceDataStoreBuilder(context, "preferences_datastore").build();
}
public void saveValue(String keyName, String Value) {
Preferences.Key<String> key = new Preferences.Key<>(keyName);
dataStore.updateDataAsync(preferences -> {
MutablePreferences mutablePreferences = preferences.toMutablePreferences();
String currentKey = preferences.get(key);
if (currentKey == null) {
saveValue(keyName, Value);
}
mutablePreferences.set(key, currentKey != null ? Value : "");
return Single.just(mutablePreferences);
}).subscribe();
}
public void getStringValue(String keyName, StringValueDelegate stringValueDelegate) {
Preferences.Key<String> key = new Preferences.Key<>(keyName);
dataStore.data().map(preferences -> preferences.get(key))
.subscribeOn(Schedulers.newThread())
.subscribe(new FlowableSubscriber<String>() {
@Override
public void onSubscribe(Subscription s) {
s.request(1);
}
@Override
public void onNext(String s) {
dataStoreManagerHandler.post(() -> stringValueDelegate.onGetValue(s));
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
});
}
public interface StringValueDelegate {
void onGetValue(String s);
}
}
I have to save and retrieve the DataStore Preferences from multiple Activities of the project using the following code.
DataStoreManager.instance.init(getApplicationContext());
DataStoreManager.instance.saveValue("schoolName", schoolName);
for retrieving
DataStoreManager.instance.getStringValue("schoolName", schoolName -> {
schoolName = schoolName;
Log.d(TAG, "onCreate: schoolName: " + schoolName);
textClasses.setText(schoolName);
});
I am facing the following error:-
You should either maintain your DataStore as a singleton or confirm that there is no two DataStore's active on the same file (by confirming that the scope is cancelled).