androidsharedpreferencesandroid-switchandroid-togglebutton

Save Switch Button State via Shared Preferences When App is Closed


In my Activity I have an Switch Button. I wanted to keep the State of the Switch Button when the App closes from the background.

The State of the Switch remains when the App is there in the Background but it goes back to the default (OFF) state when the app is cleared from the background.

I tried replicating the program from here. But I am still not able to maintain the state of the switch button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    switch1 = (Switch) findViewById(R.id.switch1);

    SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyz", MODE_PRIVATE);
    switch1.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));


    switch1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (switch1.isChecked()) {

                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                editor.putBoolean("NameOfThingToSave", true);
                editor.apply();
                switch1.setChecked(true);

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                // Setting Dialog Title
                alertDialog.setTitle("Download all the Product's PDF.");
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.pdf_alert_dialog);

                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("CANCEL",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                switch1.setChecked(false);
                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                editor.putBoolean("NameOfThingToSave", false);
                                editor.apply();

                                dialog.dismiss();
                            }
                        });
                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("DOWNLOAD ALL ",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                editor.putBoolean("NameOfThingToSave", true);
                                editor.apply();

                                
                                AlertDialog.Builder alertDialog1 = new AlertDialog.Builder(context);
                                // Setting Dialog Title
                                alertDialog1.setTitle("Free storage Available:" + megAvailable1 + " MB");
                                alertDialog1.setMessage("File size to Download: POJO MB");
                                // Setting Icon to Dialog
                                alertDialog1.setIcon(R.drawable.pdf_alert_dialog);

                                alertDialog1.setPositiveButton("CANCEL",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog1, int which) {
                                                switch1.setChecked(false);
                                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                                editor.putBoolean("NameOfThingToSave", false);
                                                editor.apply();

                                                dialog1.dismiss();
                                            }
                                        });
                                // Setting Negative "NO" Button
                                alertDialog1.setNegativeButton("DOWNLOAD  ",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog1, int which) {

                                                getFeedDownload();

                                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                                editor.putBoolean("NameOfThingToSave", true);
                                                editor.apply();

                                            }

                                        });
                                alertDialog1.show();
                            }
                        });

                // Showing Alert Message
                alertDialog.show();
            } else {
            }
        }
    });

Where am I going wrong?


Solution

  • The mistake i did was that in my onResume i had the Switch OFF. Hence, every time i restart the app the switch would go to OFF regardless of the Sharedpreference.

    I added a check to see if i had the PDF downloaded in the Downloads folder. If they were, then i just turn the switch to ON and if not then , OFF.

     @Override
    public void onResume() {
        super.onResume();
    
        Call<List<Products>> listCall = mManager.getProductsService().getAllProducts();
        //execte for the call back (asynchronous).
    
        // Now we start to execute the call
        listCall.enqueue(new Callback<List<Products>>() {
            @Override
            public void onResponse(Response<List<Products>> response, Retrofit retrofit) {
                if (response.isSuccess()) {
                    List<Products> productsList = response.body();
    
                    for (int i = 0; i < productsList.size(); i++) {
                        Products products = productsList.get(i);
                        String links = (products.getFilePath());
                        String name = products.getFileID();
                        String link = links.replaceAll("\\\\", "");
                        Log.i("linkkkkkSettings", link);
    
    
                        File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_DOWNLOADS) + "/" + name + ".pdf");
                        if (applictionFile != null && applictionFile.exists()) {
    
                            switch1.setChecked(bundle.getBoolean("ToggleButtonState", true));
                        } else {
    
                            switch1.setChecked(bundle.getBoolean("ToggleButtonState", false));
                        }
    
    
                    }
                }
            }
    
            @Override
            public void onFailure(Throwable t) {
    
            }
        });
    
    
    }