0

I have a button in my MainActivity, which opens a PopupActivity with 5 Buttons. I want that these 5 buttons change the Background Image from another Button (bSay3) in my MainActivity.

But for some reason, my App crashes when i click on one of these 5 buttons.

Here is my MainActivity Code:

public void changeColors(View v) {
    startActivity(new Intent(MainActivity.this,PopupActivity.class));}


public void ChangeColor() {
    Button bSay3 = (Button) findViewById(R.id.bSay3);
    if (Farbe == "Purple") {
        bSay3.setBackgroundResource(R.drawable.purple_3button);}
    if (Farbe == "Blue") {
        bSay3.setBackgroundResource(R.drawable.blue_3button);}
    if (Farbe == "Green") {
        bSay3.setBackgroundResource(R.drawable.green_3button);}
    if (Farbe == "Orange") {
        bSay3.setBackgroundResource(R.drawable.orange_3button);}
    if (Farbe == "Red") {
        bSay3.setBackgroundResource(R.drawable.red_3button);}
}

and my PopupActivity:

public static String Farbe;

MainActivity ma = new MainActivity();

public void ColorPurple(View v){
    Farbe = ("Purple");
    ma.ChangeColor();
}
public void ColorBlue(View v){
    Farbe = ("Blue");
    ma.ChangeColor();
}
public void ColorGreen(View v){
    Farbe = ("Green");
    ma.ChangeColor();
}
public void ColorOrange(View v){
    Farbe = ("Orange");
    ma.ChangeColor();
}
public void ColorRed(View v){
    Farbe = ("Red");
    ma.ChangeColor();
}

stack trace

1 Answers1

0

Your logic is not correct.The below piece of code does not take into consideration the instance of MainActivity ,Its basically creating another object of MainActivity.

public static String Farbe;

MainActivity ma = new MainActivity();

public void ColorPurple(View v){
    Farbe = ("Purple");
    ma.ChangeColor();
}
public void ColorBlue(View v){
    Farbe = ("Blue");
    ma.ChangeColor();
}
public void ColorGreen(View v){
    Farbe = ("Green");
    ma.ChangeColor();
}
public void ColorOrange(View v){
    Farbe = ("Orange");
    ma.ChangeColor();
}
public void ColorRed(View v){
    Farbe = ("Red");
    ma.ChangeColor();
}

In order to change the background pass the result as stated below

Intent i = new Intent(MainActivity.this,PopupActivity.class);
i.putExtra("bg_color","what ever color you want");
startActivity(i);

and in the PopUpActivity in onCreate() do as below

String bg_color = getIntent().getExtra("bg_color");

with bg_color variable now you can change the color of background.

DRY Believer
  • 1,001
  • 11
  • 20