javaandroidsharedpreferencespreferencefragment

How do i modify data on my MainActivity from Settings Activity?


I've tried many other threads and articles but I just can't find the right stuff that I am looking for. So I have a MainActivity and a SettingsActivity both are java classes. In my main activity there is a button when pressed, increases the count by +1, and shows it on a TextView, it also makes the device vibrate on every increment/Every button press. I want to make a switchpreference in SettingsActivity which if kept off/false, turns off the vibration on button press and if kept on/true, turns on the vibration on button press. I don't know how to retrieve the state of SwitchPreferenceCompat(ON OR OFF) from SettingsActivity and use it in the MainActivity, so if the user turns the switch off in setting activity, the vibration should stop on button press which is in MainActivity. I have already used Shared Preferences in MainActivity for saving the current count/number when App is closed and resumes from the same count when reopened.

MainAcitivity

package com.saad.tapcounter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {

    private AdView mAdView ;
    int Start;
    TextView txt;
    Button btnU,btnT,btnR;
    Switch sw,sw2;
    private ConstraintLayout Clayout;
    Vibrator vibe;

    Boolean switchPref;

    SharedPreferences sharedPreferences;

    private static long back_pressed;
    private Vibrator Vibrator;

    //Double Tap Exit
    @Override
    public void onBackPressed()
    {
        if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
        else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }


    //Inflater for Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
        return true;

    }

    //Menu
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()){
            case R.id.menui1:
                startActivity(new Intent(this, SettingsActivity.class));

                return true;


            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Toolbar toolbar = findViewById(R.id.toolbarid);
        setSupportActionBar(toolbar);


        MobileAds.initialize(this, "-APPID-");
        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
        Clayout = findViewById(R.id.MainLayout);
        btnT =  findViewById(R.id.tapbtn);
        btnR =  findViewById(R.id.resetbtn);
        btnU =  findViewById(R.id.undobtn);
        sw = findViewById(R.id.swch);
        sw2 = findViewById(R.id.darkswch);
        txt =  findViewById(R.id.txtv);
        txt.setTextColor(Color.BLACK);
        sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);

        loadData();
        setData();
        incrementbtn();
        undobtn();
        resetbtn();
        switchbtn();
        themeswitch();
        

    }
    public void loadData(){
        sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
    }

    private void setData(){
        Start = sharedPreferences.getInt("0",0);
        if(Start==0){
            txt.setText("0");
        }
        else{
            txt.setText(Integer.toString(Start));
        }
    }

    public void incrementbtn(){
        btnT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                incvibe();
                if (Start != 0) {
                    Start = sharedPreferences.getInt("0", 0);
                    Start += 1;
                    txt.setText(Integer.toString(Start));
                    txtresize();
                } else {
                    Start += 1;
                    txt.setText(Integer.toString(Start));
                }
                sharedPreferences.edit().putInt("0", Start).apply();
            }
        });
    }

    public void undobtn(){
        btnU.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                undovibe();
                if (Start != 0) {
                    Start = sharedPreferences.getInt("0", 0);
                    Start -= 1;
                    txt.setText(Integer.toString(Start));
                }
                else{
                    return;
                }
                sharedPreferences.edit().putInt("0", Start).apply();
            }
        });
    }

    public void resetbtn(){
        btnR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetvibe();
                Start = 0;
                txt.setText(Integer.toString(Start));
                sharedPreferences.edit().putInt("0", Start).apply();

            }
        });
    }

    public void switchbtn(){
        sw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sw.isChecked()) {
                    btnR.setEnabled(false);
                    btnT.setEnabled(false);
                    btnU.setEnabled(false);
                    txt.setTextColor(Color.RED);
                }
                else{
                    btnR.setEnabled(true);
                    btnT.setEnabled(true);
                    btnU.setEnabled(true);
                    if(sw2.isChecked()){
                        txt.setTextColor(Color.WHITE);
                    }
                    else{
                        txt.setTextColor(Color.BLACK);
                    }
                }
            }
        });
    }

    public void themeswitch(){
        sw2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sw2.isChecked()){
                    Clayout.setBackgroundColor(Color.DKGRAY);

                    if(sw.isChecked()){
                        txt.setTextColor(Color.RED);
                    }
                    else{
                        txt.setTextColor(Color.WHITE);
                    }
                }
                else{
                    Clayout.setBackgroundColor(Color.WHITE);
                    if(sw.isChecked()){
                        txt.setTextColor(Color.RED);
                    }
                    else{
                        txt.setTextColor(Color.BLACK);
                    }

                }
            }
        });

    }

    public void txtresize(){

        if(Start > 1000 && Start < 10000){
            txt.setTextSize(80);
        }
        else if (Start > 10000 && Start < 100000){
            txt.setTextSize(60);
        }
        else if (Start > 100000){
            txt.setTextSize(40);
        }
        else{
            return;
        }
    }
    StringBuilder info = new StringBuilder();


    public void undovibe(){
        vibe.vibrate(100);
    }

    public void resetvibe(){
        vibe.vibrate(150);
    }

    public void incvibe(){
        vibe.vibrate(40);
    }

}//Real one

SettingActivity (created it from NEW > SettingActivity) I did try some stuff by myself in here but it crashed my app.

package com.saad.tapcounter;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

        }
    }



}

root_preference.xml

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory app:title="Settings"
        app:iconSpaceReserved="false">

        <SwitchPreferenceCompat
            app:key="Switchsett1"
            app:title="Vibration"
            app:summaryOff="Turn Vibration On"
            app:summaryOn="Turn Vibration Off"
            app:iconSpaceReserved="false"
            app:defaultValue="true"
            />

        <SwitchPreferenceCompat
            app:key="Switchset2"
            app:iconSpaceReserved="false"
            app:summaryOff="@string/attachment_summary_off"
            app:summaryOn="@string/attachment_summary_on"
            app:title="@string/attachment_title" />

    </PreferenceCategory>

</PreferenceScreen>

Solution

  • I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity

    To get the value of SwitchPreferenceCompat from shared preference, then you need to retrieve it as a Boolean

    Now the key of your first SwitchPreferenceCompat is Switchsett1, so to retrieve the value of this:

    public class MainActivity extends AppCompatActivity {
    
        Boolean switchPref;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ....
    
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            switchPref = prefs.getBoolean("Switchsett1", false);
            Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.
    

    Now the Toast in the above script shows true if the SwitchPreferenceCompat is ON, and false if it's OFF.

    You can do the same for Switchset2 SwitchPreferenceCompat