3

I've got a problem with setting a background image programmatically. I cannot do it.

This is my theme class. There are radio buttons in the code that should change the main background. So far I've written implementation for two radio buttons (i.e. radioButtonMountains and radioButtonSea) that should load two different images (i.e. mountains.png and sea.png).

public class ThemeActivity extends BasicActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_theme);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Motywy");
        
        setAction();
    }
    
    private void setAction(){
        
        relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid);
        
        radioGroup=(RadioGroup) findViewById(R.id.radioGroup);
        radioButtonMountains=(RadioButton) findViewById(R.id.radioMountains);
        radioButtonCity=(RadioButton) findViewById(R.id.radioCity);
        radioButtonSea=(RadioButton) findViewById(R.id.radioSea);
        radioButtonNature=(RadioButton) findViewById(R.id.radioNature);
        
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if(radioButtonMountains.isChecked()){
                
                    //relativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.mountains));
                    //relativeLayout.setBackground(getResources().getDrawable(R.drawable.mountains));
                    relativeLayout.setBackgroundResource(R.drawable.mountains);                 
            }
            else if(radioButtonCity.isChecked()){
                
            }
            else if(radioButtonSea.isChecked()){
                relativeLayout.setBackgroundResource(R.drawable.sea);
            }
            else if(radioButtonNature.isChecked()){
                
            }

        }
    });             
}

This is my activity_main.xml for my main class (if you want i can paste the code with my main class). I've added 'android:id="@+id/relativeLayoutid"' which is referred to above.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayoutid" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/sea"
    android:orientation="vertical" >

// other things like a ImageButton, a TextView etc

</RelativeLayout>

Finally, when I click, one of the radio buttons is replaced by:

11-11 21:28:34.172: D/AndroidRuntime(22316): Shutting down VM
11-11 21:28:34.172: W/dalvikvm(22316): threadid=1: thread exiting with uncaught exception (group=0x411162a0)
11-11 21:28:34.202: E/AndroidRuntime(22316): FATAL EXCEPTION: main
11-11 21:28:34.202: E/AndroidRuntime(22316): java.lang.NullPointerException
11-11 21:28:34.202: E/AndroidRuntime(22316):    at com.example.runapp.ThemeActivity$1.onCheckedChanged(ThemeActivity.java:43)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioGroup.setCheckedId(RadioGroup.java:174)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioGroup.access$600(RadioGroup.java:54)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:358)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.CompoundButton.setChecked(CompoundButton.java:140)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.CompoundButton.toggle(CompoundButton.java:92)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioButton.toggle(RadioButton.java:76)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.CompoundButton.performClick(CompoundButton.java:104)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.view.View$PerformClick.run(View.java:17082)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.os.Handler.handleCallback(Handler.java:615)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.os.Looper.loop(Looper.java:137)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.app.ActivityThread.main(ActivityThread.java:4867)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at java.lang.reflect.Method.invokeNative(Native Method)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at java.lang.reflect.Method.invoke(Method.java:511)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at dalvik.system.NativeStart.main(Native Method)

and the application closed. I tried use this way:

relativeLayout.setBackgroundResource(R.drawable.mountains);

and this way:

relativeLayout.setBackground(getResources().getDrawable(R.drawable.mountains));

and this way:

relativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.mountains));

and none of them work.

How can i fix this issue? What should i correct?

The solution:

  1. Move the relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid) and setBackgroundResource() method to the main activity behind setContentView() method.
  2. Create a static variable and put this varaible in the setBackgroundResource() method as the parameter.
  3. Change the static variable in theme activity where you've got radio buttons.

MainActivity class:

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MainActivity extends BasicActivity implements OnClickListener {

    public final static String EXTRA_MESSAGE = "com.example.helloworld.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //other things
        
        setContentView(R.layout.activity_main);
        
        relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid);
        
        if(image==0) relativeLayout.setBackgroundResource(R.drawable.mountains);
        else relativeLayout.setBackgroundResource(image);

        //other things
    }

    //other things
    
    public RelativeLayout relativeLayout;
    public static int image;
}

activity_main.xml for MainActivity class:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayoutid" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/sea"
    android:orientation="vertical" >

// other things like a ImageButton, a TextView etc

</RelativeLayout>

ThemeActivity class where I change the main background:

public class ThemeActivity extends BasicActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_theme);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Theme");

        setAction();
    }
    
    private void setAction(){
        
        radioGroup=(RadioGroup) findViewById(R.id.radioGroup);
        radioButtonMountains=(RadioButton) findViewById(R.id.radioMountains);
        radioButtonCity=(RadioButton) findViewById(R.id.radioCity);
        radioButtonSea=(RadioButton) findViewById(R.id.radioSea);
        radioButtonNature=(RadioButton) findViewById(R.id.radioNature);

        setRadioChoose();
        
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                
                if(radioButtonMountains.isChecked()){
                    
                    MainActivity.image=R.drawable.mountains;
                }
                else if(radioButtonCity.isChecked()){
                    
                    MainActivity.image=R.drawable.city;
                }
                else if(radioButtonSea.isChecked()){
                    
                    MainActivity.image=R.drawable.sea;                  
                }
                else if(radioButtonNature.isChecked()){

                    MainActivity.image=R.drawable.nature;   
                }

                saveRadioChoose(checkedId);
            }
        });
        
    }
    
    private void setRadioChoose(){
        
        radioChoose=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        radioChooseEdit=radioChoose.edit();
        
        int radio=radioChoose.getInt("RADIO", 0);
        
        if(radio==radioButtonMountains.getId()) radioButtonMountains.setChecked(true);
        else if(radio==radioButtonCity.getId()) radioButtonCity.setChecked(true);
        else if(radio==radioButtonSea.getId()) radioButtonSea.setChecked(true);
        else if(radio==radioButtonNature.getId()) radioButtonNature.setChecked(true);
        else if(radio==0) radioButtonMountains.setChecked(true);
    }
    
    private void saveRadioChoose(int checkedId){
        
        radioChooseEdit.putInt("RADIO", checkedId);
        radioChooseEdit.commit();
    }
    
    private RadioGroup radioGroup;
    private RadioButton radioButtonMountains;
    private RadioButton radioButtonCity;
    private RadioButton radioButtonSea;
    private RadioButton radioButtonNature;
    
    private SharedPreferences radioChoose;
    private SharedPreferences.Editor radioChooseEdit;
}
Intermaker
  • 15
  • 5
Robert
  • 762
  • 2
  • 10
  • 23
  • See the following SO answer... [Hope this can be of help][1] [1]: http://stackoverflow.com/questions/12678949/android-set-layout-background-programmatically – Mario Norato Nov 11 '14 at 22:20
  • Stick a debug point in the onCheckedChanged() listener and when it is hit see if all the RadioButton objects are set properly. – James Cross Nov 11 '14 at 22:20
  • what is in the line 43 of your ThemeActivity ? – Houcine Nov 11 '14 at 22:37
  • @Houcine: in the line 43 is: relativeLayout.setBackgroundResource(R.drawable.mountains); – Robert Nov 11 '14 at 22:41
  • the relativeLayout variable is null. because you have a NullPointerException. check if the relativeLayout is different from null and display logs, or try to debug it. and before doing this, clean your project. – Houcine Nov 11 '14 at 22:43
  • @Houcine: thanks for your advice, i'll try this and let you know. Just now i checked the relativeLayout variable. You're right, it's null. Have you got any idea why? I've got a "relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid);" so this variable shouldn't be null. – Robert Nov 12 '14 at 00:00
  • the reason of this nullpointerException could be a wrong id of your RelativeLayout , or your view that you try to find by its id is in another layout different from the one you set as a contentView of your Activity. the second reason is calling findViewById() before setContentView(int layoutResId). Try to modify the Id of your relativeLayout and if it exists on your layout xml file .Then clean your project. – Houcine Nov 12 '14 at 10:55
  • @Houcine: thanks for your help. It works! I've added relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid) and setBackgroundResource() method in my main activity instead of my theme activity. I've moved these things behind setContentView() method. Finally I've created a static variable which is placed as the setBackgroundResource() method parameter and i change this static variable in my theme activity where I've got radio buttons. I've edited my main post and i've put there a solution. – Robert Nov 14 '14 at 13:49
  • @Maniek : you're welcome, glad that it works for you. – Houcine Nov 14 '14 at 22:39

2 Answers2

1

I used this code for a shopping cart//catalog app. The radiobuttons were used to hold the product color information, so a user selecting a color, represented by a radiobutton with a different color background, determined the product color of the image.

 color[i] = new RadioButton(getActivity());
 color[i].setButtonDrawable(R.drawable.color_radio_button);
 if (sdkVersion < 16) {
    color[i].setBackgroundDrawable(bkg);
 } else {
    color[i].setBackground(bkg);
 }

Drawable

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

<item android:drawable="@drawable/color_radio_selected" android:state_focused="true"/>
<item android:drawable="@drawable/color_radio_selected" android:state_pressed="true"/>
<item android:drawable="@drawable/color_radio_selected" android:state_selected="true"/>
<item android:drawable="@drawable/color_radio_selected" android:state_checked="true"/>
<item android:drawable="@drawable/color_radio_unselected"/>

</selector>

Image

enter image description here

Martin
  • 4,711
  • 4
  • 29
  • 37
1

final RelativeLayout imageView = (RelativeLayout) mLockscreenView.findViewById(R.id.mainImage); imageView.setBackgroundResource(R.drawable.bgg);