RadioGroup中RadioButton的SharedPreferences。

时间:2020-06-14 22:04:00

标签: java android radio-button

如何对单选组中的单选按钮使用共享的首选项。我有两个按钮(下一个和上一个)。我想在用户转到下一个并再次回到上一个时间时检查用户选择的选项

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private String TAG = "MainActivity ----- ; " ;
    // Store instance variables

    private int page;
    private ConsentForm form;

    ListView listView;
    ListViewAdapter adapter;
    String[] title;
    String[] description;
    int[] icon;
    ArrayList<Model> arrayList = new ArrayList<Model>();


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

        //initialize preferences
        PreferenceUtils.initialize(getApplicationContext());

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Redeemed Songs");

        title = new String[]{"Song 001 | This song lyrics 1","Song 002 | This song lyrics 2","Song 003 | This song lyrics 3","Song 004 | This song lyrics 4","Song 005 | This song lyrics 5","Song 006 | This song lyrics 6","Song 007 | This song lyrics 7"};

        description = new String[]{"MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song",};

        icon = new int[]{ R.drawable.song, R.drawable.song, R.drawable.song, R.drawable.song,R.drawable.song,R.drawable.song, R.drawable.song,};

        listView = findViewById(R.id.list);

        for (int i =0; i<title.length; i++){
            Model model =new Model(title[i], description[i], icon[i]);
            //let's simply say, the song identifier is just the order of the song in the list
            model.id = i;
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass result to listview class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview class
        listView.setAdapter(adapter);



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)){
                    adapter.filter("");
                    listView.clearTextFilter();
                }
                else {
                    adapter.filter(s);
                }
                return true;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==R.id.action_settings){
            Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main2Activity.class));
            return true;
            //do your funtionality here

        }
        else if (id==R.id.action_howtouse){
                Toast.makeText(this, "How-To", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here


        }else if (id==R.id.action_favorites){
                Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here


        }
        else if (id==R.id.action_developers){
            Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main4Activity.class));
            return true;
            //do your funtionality here

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
}

////// log cat ,,,,我的代码错误

 radioGroup = findViewById( R.id.radioGroup );
       radioGroup.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(RadioGroup group, int checkedId) {
               ToggleableRadioButton radioButton = (ToggleableRadioButton) group. findViewById(checkedId);
               int checkedIndex = group.indexOfChild(radioButton);
               SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
               SharedPreferences.Editor editor = sharedPreferences.edit();
               editor.putInt("check", checkedIndex);
               editor.apply();
           }
       } );




 private void Update(){
        SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
        int savedRadioIndex = sharedPreferences.getInt("check", 0);
        System.out.println("savedRadioIndex is "+savedRadioIndex);
        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
       ToggleableRadioButton savedCheckedRadioButton = (ToggleableRadioButton) radioGroup.getChildAt(savedRadioIndex);
        savedCheckedRadioButton.setChecked(true);//error on this line


    }

布局/////////////这是layou,其中显示了RadioGroup和单选按钮


Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.quiz.ToggleableRadioButton.setChecked(boolean)' on a null object reference

1 个答案:

答案 0 :(得分:0)

尝试

在布局文件中

<RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       >

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton2" />
    </RadioGroup>

活动中

String radiovalue=null; //globally declared

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.radioButton:
                       radiovalue= R1.getText().toString();//R1 is radiobutton1
                        break;
                    case R.id.radioButton2:
                         radiovalue= R2.getText().toString();//R2 is radiobutton2
                        break;
                }
            }
        });

之后,将radiovalue设置为共享首选项。 调用共享首选项值时,只需检查值并根据其启用单选按钮即可。