Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.
This is what I get when I run the program and I don't know what to do. I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.
package com.example.gia.applumini;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
bgElement.setBackgroundColor(Color.RED);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
int color = ((ColorDrawable) bgElement.getBackground()).getColor();
if (color == Color.RED) {
bgElement.setBackgroundColor(Color.BLUE);
}
else {
bgElement.setBackgroundColor(Color.RED);
}
}
});
}
}