0

I want to save data using DataStore, here is my implementation:

android {
    namespace 'com.Test'
    compileSdk 33
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.Test"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
dependencies {
    //DataStore instead of SharedPreferences
    implementation "androidx.datastore:datastore-preferences:1.0.0"
    //RxJava2 support
    implementation "androidx.datastore:datastore-preferences-rxjava2:1.0.0"
}

This is the class I used to read and write to DataStore:

public class DataStoreUtiles {
    private RxDataStore<Preferences> dataStoreValue=null;
    private Preferences pref_error = new Preferences() {
        @Nullable
        @Override
        public <T> T get(@NonNull Key<T> key) {
            return null;
        }

        @Override
        public <T> boolean contains(@NonNull Key<T> key) {
            return false;
        }

        @NonNull
        @Override
        public Map<Key<?>, Object> asMap() {
            return null;
        }
    };
    
    public DataStoreUtiles(Context c){
        dataStoreValue = new RxPreferenceDataStoreBuilder(c,"MySettings").build();
    }

    public String GetServerStatus(){
        try {
            Preferences.Key<String> ServerStatusKey = PreferencesKeys.stringKey("ServerStatus");
            Flowable<String> Status =
                    dataStoreValue.data().map(prefs -> prefs.get(ServerStatusKey)).onErrorReturnItem("None");
            return   Status.blockingFirst();
        }catch (Exception ex){
            return "Error:"+ex.getMessage();
        }
    }

    public String SetServerStatus(String Status){
        try {
            Single<Preferences> updateResult =  dataStoreValue.updateDataAsync(prefsIn -> {
                MutablePreferences mutablePreferences = prefsIn.toMutablePreferences();
                Preferences.Key<String> ServerStatusKey = PreferencesKeys.stringKey("ServerStatus");

                mutablePreferences.set(ServerStatusKey,Status);
                return Single.just(mutablePreferences);
            }).onErrorReturnItem(pref_error);

            if(updateResult.blockingGet() == pref_error){
                return "Error";
            }
            
            return "1";
        }catch (Exception ex){
            return ex.getMessage();
        }
    }
}

and I call the class in MainActivity:

private CheckBox StartStopServer;
private DataStoreUtiles DataStore = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        DataStore = new DataStoreUtiles(this);
        StartStopServer = (CheckBox) findViewById(R.id.CHBox_StartStopServer);
        String ServerStatus=DataStore.GeteServerStatus();
        if(ServerStatus == "1"){
            StartStopServer.setChecked(true);
        }else if(ServerStatus == "-1"){
            StartStopServer.setChecked(false);
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("No Setting was saved.");
            final AlertDialog alert = builder.create();
            alert.show();
        }
        
        StartStopServer.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                DataStore.SetServerStatus("1");

            } else {
                DataStore.SetServerStatus("-1");
            }
        });
    }
}

I tested the application on Noxplayer, when I opened the application and checked the checkbox the data is saved. But when I close and open the application again, no data was saved.

I want to create DataStore if it doesn't exist

dataStoreValue = new RxPreferenceDataStoreBuilder(c,"MySettings").build();

Does this line create a Datastore every time I call it or open it if exist and create it if not exist? please provide me solution in java.

3
  • youtu.be/wDOZ7tc7rT4 Commented Jul 21, 2023 at 6:51
  • Thanks for the video but it says in Kotlin and i want it in java also he did not explain the code beside dark theme not clear Commented Jul 21, 2023 at 7:23
  • No i back to using Shared Preferences Commented Jan 9, 2024 at 0:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.