Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

How to implement Datastore in java based android app?

I can only find ways to implement datastore through Kotlin. I have tried creating it with DataStore<Preferences> datastore = new Datastore<Preferences> but as soon as proceed with it, it overrides to methods namely save and loadData but the parameters passed in them are also in Kotlin. Should I proceed with Sharedpreferences only?

question from:https://stackoverflow.com/questions/66067126/how-to-implement-datastore-in-java-based-android-app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are few steps to implement dataStore in java base.

First and foremost, it is good to notice that there are 2 different types of dependencies for the datastore.

  1. TYPED datastore
  2. Preferences DataStore (SharedPreferences like APIs)

Here are some steps to implement the latter one in the java based application.

1. Implementation

// Preferences DataStore (SharedPreferences like APIs)
dependencies {
  implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06"

  // RxJava3 support
  implementation "androidx.datastore:datastore-preferences-rxjava3:1.0.0-alpha06"
} 

2. Create a Preferences DataStore

DataStore<Preferences> dataStore =
  new RxPreferenceDataStoreBuilder(context, /*name=*/ "settings").build();

3. Write to a Preferences DataStore

Single<Preferences> updateResult =  RxDataStore.updateDataAsync(dataStore, 
prefsIn -> {
  MutablePreferences mutablePreferences = prefsIn.toMutablePreferences();
  Integer currentInt = prefsIn.get(INTEGER_KEY);
  mutablePreferences.set(INTEGER_KEY, currentInt != null ? currentInt + 1 : 1);
  return Single.just(mutablePreferences);
});

// The update is completed once updateResult is completed.

3. Read from a Preferences DataStore

Preferences.Key<Integer> EXAMPLE_COUNTER = PreferencesKeys.int("example_counter");

Flowable<Integer> exampleCounterFlow =
  RxDataStore.data(dataStore).map(prefs -> prefs.get(EXAMPLE_COUNTER));

if you want to do more complex please checkout the full documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...