java – Android SharedPreferences com RadioButton

Question:

I have two RadioButtons, I want to select one of them, close the app and when it opens load the last selection.

Can you help me? I can't find a clear tutorial explained.

Thanks.

Answer:

The example I'm going to give is with checkbox , but the method is no different, just change it to your radiobutton .

Create a preference class. There you can store everything you want.
Here's my example:

public class Preferencia {
    public static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences("energy", Context.MODE_PRIVATE);
    }

  //// preferencia de checkbox
   public static boolean setcbremember(Context context, boolean a) {
        SharedPreferences sharedPref = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("Cbremember", a);
        editor.commit();
        return a;

    }
    public static boolean getcbremember(Context context) {
        SharedPreferences sharedPref = getSharedPreferences(context);
        return sharedPref.getBoolean("Cbremember", true);
    }
 //// Deletar preferencia de login e senha
        public static void deletar(Context context, String login) {
        SharedPreferences sharedPref = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.clear();
        editor.commit();

    }

}

Where I save the checkbox , change it to the radiobutton and with an if and else, assign to the shared what the user chooses.

Here is where I receive the checkbox to assign the preference:

public void btnentrarclick(View currentButton) {

        if(cbremember.isChecked()) {
            AcessoLogin ac = new AcessoLogin(Tela_de_Login.this,
                    edtlogin.getText().toString(), edtsenha.getText().toString());
            Preferencia.setlogin(Tela_de_Login.this, edtlogin.getText().toString());
            Preferencia.setsenha(Tela_de_Login.this, edtsenha.getText().toString());
            Preferencia.setcbremember(Tela_de_Login.this, cbremember.isChecked());

            ac.execute("");
        }
        else{

            AcessoLogin ac = new AcessoLogin(Tela_de_Login.this,
                    edtlogin.getText().toString(), edtsenha.getText().toString());
            Preferencia.deletar(Tela_de_Login.this, edtlogin.getText().toString());
            Preferencia.deletar(Tela_de_Login.this, edtsenha.getText().toString());

            ac.execute("");
        }

    }

In my case, as you can see, if the user chooses the checkbox activated, it will save the user's information, if he unchecks the checkbox, he will not save and delete what was saved.
I hope it helped you

Scroll to Top