문제

Sorry for my bad english.

I have 2 classes,

1 MainActivity.java (Standard) 2 settings.java (for settings)

I have a RadioGroup with 5 Radiobuttons.

I save the state of the radio buttons as follows (in to settings.java class):

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    SharedPreferences settings = getSharedPreferences("status", 0); 
    SharedPreferences.Editor editor = settings.edit();

    editor.putBoolean("blue", blue.isChecked());
    editor.putBoolean("orange", orange.isChecked());
    editor.putBoolean("purple", purple.isChecked());
    editor.putBoolean("grey", grey.isChecked());
    editor.putBoolean("green", green.isChecked());
    editor.commit();

}


public void loadSettings () {



    SharedPreferences settings = getSharedPreferences("status", 0);

    royalBlue.setChecked(settings.getBoolean("blue", false)); 
    orange.setChecked(settings.getBoolean("orange", false));
    purple.setChecked(settings.getBoolean("purple", false));
    titan.setChecked(settings.getBoolean("grey", false));
    eighties.setChecked(settings.getBoolean("green", false));

}

the status of the radio buttons is saved successfully. Even after a restart of the app the radio button is saved.

I would like now when the RadioButton orange (or other) is selected, the ImageButton will change my image. I would like to make in the MainActivity.

I have tried it in the Main Activity so but I always get a NullPoinException:

Code from the Main ...

private settings load = new settings();
...
...
public void change (){
   if (load.orange.isChecked()){
        imBuOn.setImageResource(R.drawable.orange);
    }

as I said I can so unfortunately unable to access the status of the radio button.

Do I need to maybe use PreferenceManager? how shall I put it best?

도움이 되었습니까?

해결책

You don't need to create an instance of the settings class and fetch the value of the checkBox. Instead, you should just use the same code as given in the loadSettings method since you are just accessing the SharedPreferences file.

So, in your MainActivity, just run this

private void checkAndSetImage()
{
     SharedPreferences settings = getSharedPreferences("status", 0);
     if(settings.getBoolean("orange", false))
     {
         imBuOn.setImageResource(R.drawable.orange);
     }
}

Just call this function to wherever applicable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top