0

Trying to have three radio buttons show up as menu items where the user picks only one and that choice is saved even if the app is closed. The choice they pick will then be used to determine which layout fragment will be displayed when the app starts up.

Don't really understand how to save the user choice in shared preferences as I have never used it before and new to coding.

My Menu Layout is

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/settings"
    android:title="@string/settings">
    <menu >
        <group android:id="@+id/startScreenGroup" android:checkableBehavior="single">
            <item android:id="@+id/submenu0" android:title="Fragment 0" />
            <item android:id="@+id/submenu1" android:title="Fragment 1" />
            <item android:id="@+id/submenu2" android:title="Fragment 2" />
        </group>
    </menu>
</item>

</menu>
DC5Gator
  • 65
  • 1
  • 9

2 Answers2

1

Try the following code, It's not tested but basically this is how it usually would be, please let me know if there's any errors that occur when trying my code.

private RadioGroup radioGroup;
private RadioButton radioButton;

//Fragment references
private Fragment0 fragment0;
private Fragment1 fragment1;
private Fragment2 fragment2;

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

        //Create a SharedPreference variable
        SharedPreferences appPreferences = this.getSharedPreferences("YOUR APP PACKAGE NAME", Context.MODE_PRIVATE);


        final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.startScreenGroup);
       radioGroup.setOnChangedListener(new RadioGroup.OnChangedListener() {

          @Override
         void onCheckedChanged(RadioGroup group, int checkedId) {

            switch (checkedId) {

            case R.id.submenu0:
                 appPreferences.edit().putString("LoadFragment","submenu0");
                 break;
            case R.id.submenu1:
                 appPreferences.edit().putString("LoadFragment","submenu1");
                 break;
            case R.id.submenu2:
                appPreferences.edit().putString("LoadFragment","submenu2");
                break;
             }

        appPreferences.commit();        
    }
});


        //get menuID
        String fragmentToLoad = appPreferences.getString("LoadFragment","");

       //load user selected fragment
       if(fragmentToLoad != null){

       switch(fragmentToLoad){
          case "submenu0" : 
          this.getSupportFragmentManager().beginTransaction()
              .replace(R.id.container_main, fragment0)
              .commit();
              break;

         case "submenu1" : 
         this.getSupportFragmentManager().beginTransaction()
             .replace(R.id.container_main, fragment1)
             .commit();
             break;

         case "submenu2" : 
         this.getSupportFragmentManager().beginTransaction()
             .replace(R.id.container_main, fragment2)
             .commit();
              break;
        }
   }


}

UPDATE

I finally got some time to work on this, 100% working and tested on 2 mobiles (Lollipop and Marshmallow devices).

public class MainActivity extends AppCompatActivity {

    SharedPreferences appPreferences;

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

        //Create a SharedPreference variable
        appPreferences = this.getSharedPreferences("com.example.ramithrd.radiobuttonssharedpref", Context.MODE_PRIVATE);

        //get menuID
        String fragmentToLoad = appPreferences.getString("LoadFragment","");

        //load user selected fragment
        if(fragmentToLoad != null){

            switch(fragmentToLoad){
                case "submenu0" :
                    this.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container_main, new Fragment0())
                            .commit();
                    break;

                case "submenu1" :
                    this.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container_main, new Fragment1())
                            .commit();
                    break;

                case "submenu2" :
                    this.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container_main, new Fragment2())
                            .commit();
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.submenu0) {
            appPreferences.edit().putString("LoadFragment","submenu0").commit();
            this.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container_main, new Fragment0())
                    .commit();

        } else  if (id == R.id.submenu1) {
            appPreferences.edit().putString("LoadFragment","submenu1").commit();
            this.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container_main, new Fragment1())
                    .commit();
        } else if (id == R.id.submenu2){
            appPreferences.edit().putString("LoadFragment","submenu2").commit();
            this.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container_main, new Fragment2())
                    .commit();
        }


        return super.onOptionsItemSelected(item);
    }
}
RamithDR
  • 2,103
  • 2
  • 25
  • 34
  • Tried but getting a null point exception on the radio listener. Maybe because my radio buttons are inside a menu? I'm also using a pager adapter for my fragments. I was initially using viewPager.setCurrentItem(1); to make it load a specific page and thought I could just replace the 1 with an integer from shared pref based on user input. – DC5Gator Aug 27 '16 at 19:18
  • Works like a charm! Thanks! – DC5Gator Aug 28 '16 at 16:02
0

Your radio group will need a callback that's triggered when the user clicks an item. In that callback, you can save the clicked value to a SharedPreference.

  1. In the onCreate() method of your Activity, find your RadioGroup and assign it an OnCheckedChangedListener.
  2. In the listener onCheckChanged() method, check which item the user clicked.
  3. Use a SharedPreferences.Editor to save it to disk.

Your code will look something like this (not complied or tested):

public void onCreate(final Bundle savedInstanceBundle) {

    final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.startScreenGroup);
    radioGroup.setOnChangedListener(new RadioGroup.OnChangedListener() {
        @Override
        void onCheckedChanged(RadioGroup group, int checkedId) {
            SharedPreferences.Editor editor = getPreferenceManager().getSharedPreferences().edit();
            switch (checkedId) {
                case R.id.submenu0:
                    editor.putString("my_key", "menu0");
                    break;
                case R.id.submenu1:
                    editor.putString("my_key", "menu1");
                    break;
                case R.id.submenu2:
                    editor.putString("my_key", "menu2");
                    break;
            }
            editor.commit();        
        }
    });

}
Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
  • will radio group retain its state when activity reloaded? Because we are not saving selected-id in preferences, how can we set selected option back? – kiranking Mar 09 '19 at 14:43