Search code examples
javaandroidandroid-webviewsharedpreferences

How to add SharedPreferences


I'm a beginner in programming! Now, I'm working with android apps in Android Studio. I have tried to make three buttons that they help to link three HTML pages via webview. But, there is a problem that I can't be adding Shared Preferences to save the clicked button. If I reenter the app, changes are not being saved. Here is my Main Activity:

package com.example.myapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatRadioButton;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    WebView view;
    AppCompatRadioButton rbLeft, rbRight, rbCenter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rbLeft = findViewById(R.id.rbLeft);
        rbRight = findViewById(R.id.rbRight);
        rbCenter = findViewById(R.id.rbCenter);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        view = (WebView) this.findViewById(R.id.webView);
        view.getSettings().setJavaScriptEnabled(true);
        view.getSettings().setLoadsImagesAutomatically(true);
        view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        view.loadUrl("file:///android_asset/index1.html");

    }

    private class MyBrowser extends WebViewClient implements com.example.myapp.MyBrowser {
        @Override
        public boolean shouldOverrideurlLoading(WebView view, String url){
            view.loadUrl(url);
            return true;
        }
    }

    public void onRadioButtonClicked(View views){
        boolean isSelected = ((AppCompatRadioButton)views).isChecked();
        switch (views.getId()){
            case R.id.rbLeft:
                if (isSelected){
                    rbLeft.setTextColor(Color.WHITE);
                    rbRight.setTextColor(Color.RED);
                    rbCenter.setTextColor(Color.RED);
                    view.loadUrl("file:///android_asset/index1.html");
                }
                break;
            case R.id.rbCenter:
                if (isSelected){
                    rbLeft.setTextColor(Color.RED);
                    rbRight.setTextColor(Color.RED);
                    rbCenter.setTextColor(Color.WHITE);
                    view.loadUrl("file:///android_asset/info.html");

                }
                break;
            case R.id.rbRight:
                if (isSelected){
                    rbLeft.setTextColor(Color.RED);
                    rbRight.setTextColor(Color.WHITE);
                    rbCenter.setTextColor(Color.RED);
                    view.loadUrl("file:///android_asset/qollanma.html");


                }
                break;

        }

    }

    boolean doubleBackToExitPressedOnce;

    @Override
    public void onBackPressed() {

        if (doubleBackToExitPressedOnce) {
            new AlertDialog.Builder(this)
                    .setTitle("Halal Check")
                    .setMessage("Dasturdan chiqmoqchimisiz?")
                    .setPositiveButton("Ha",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    finish();
                                }

                            }).setNegativeButton("Yo'q", null).show();
            return;
        } else {
            if (view.canGoBack()) {
                view.goBack();
            } else {
            }
        }

        this.doubleBackToExitPressedOnce = true;
        if (getApplicationContext() == null) {
            return;
        } else {
            Toast.makeText(this, "Iltimos, Dasturdan chiqish uchun yana bir marta bosing!",
                    Toast.LENGTH_SHORT).show();
        }
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }
}


Please, If anyone knows about this, help me! If it is possible, please show, how will it be in my code. Thank you for your attention!


Solution

  • If I am understanding your goal right, this will be how you can achieve your goal.

    1. Once radio button has selected, app will save which radio button was selected to SharedPreferences.
    2. When app loaded next time, it will check SharedPreferences value and load appropriate HTML file.

    So, on your onRadioButtonClicked(), you can add following code that saves which radio button was pressed:

    public void onRadioButtonClicked(View views){
        boolean isSelected = ((AppCompatRadioButton) views).isChecked();
        SharedPreferences sharedPref = getSharedPreferences("omg", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
    
        switch (views.getId()){
            case R.id.rbLeft:
                if (isSelected){
                    rbLeft.setTextColor(Color.WHITE);
                    rbRight.setTextColor(Color.RED);
                    rbCenter.setTextColor(Color.RED);
                    view.loadUrl("file:///android_asset/index1.html");
                    editor.putString("last_button", "rbLeft");
                    editor.apply();
                }
                break;
    
            case R.id.rbCenter:
                if (isSelected){
                    rbLeft.setTextColor(Color.RED);
                    rbRight.setTextColor(Color.RED);
                    rbCenter.setTextColor(Color.WHITE);
                    view.loadUrl("file:///android_asset/info.html");
                    editor.putString("last_button", "rbCenter");
                    editor.apply();
                }
                break;
    
            case R.id.rbRight:
                if (isSelected){
                    rbLeft.setTextColor(Color.RED);
                    rbRight.setTextColor(Color.WHITE);
                    rbCenter.setTextColor(Color.RED);
                    view.loadUrl("file:///android_asset/qollanma.html");
                    editor.putString("last_button", "rbRight");
                    editor.apply();
                }
                break;
    
        }
    
    }
    

    This code will generate (if there is no matching SharedPreference) or save (if there is matching SharedPreference) a SharedPreference named "omg", and put a value radio button name with key name "last_button" in your device storage like this:

    └ data\data\com.example.package\shared_prefs
        - omg.xml
    
    └ data\data\com.example.package\shared_prefs\omg.xml
    ...
    <string name="last_button">rbLeft</string>
    ...
    

    So, the last thing is to load SharedPreference value when app is loaded. On your onCreate():

    ...
    view.getSettings().setSomeSettings();
    view.setScrollBarStyle(Blabla);
    
    SharedPreferences sharedPref = getSharedPreferences("omg", Context.MODE_PRIVATE)
    switch (sharedPref.getString("last_button", "This will be the value when there was no matching key.") {
        case "rbLeft":
            rbLeft.setChecked(true);
            view.loadUrl("file:///android_asset/index1.html");
            break;
    
        case "rbCenter":
            rbCenter.setChecked(true);
            view.loadUrl("file:///android_asset/info.html");
            break;
    
        case "rbRight":
            rbRight.setChecked(true);
            view.loadUrl("file:///android_asset/qollanma.html");
            break;
    
        case "This will be the value when there was no matching key.":
            throw IllegalStateException("There was no matching key in omg SharedPreference.");
            break;
    
    }