New to programming android apps and keep getting a null pointer exception and im not sure why. Ive ressearched this a bit and it seems that most people get this because of the setContentView but it seems that from what everyone else is saying my setContentView is in the right space etc…
int randInt;
int[] randColor = {Color.RED,Color.BLUE,Color.GREEN,Color.YELLOW,Color.BLACK,
Color.CYAN,Color.MAGENTA,Color.LTGRAY,Color.DKGRAY,Color.WHITE};
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
View layout = findViewById(R.layout.activity_main);
layout.setOnTouchListener(this);
textView1 = (TextView) findViewById(R.id.textView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
setBackGroundColor(randInt);
}
@Override
public boolean onTouch(View v, MotionEvent e){
float xPos = e.getX();
float yPos = e.getY();
changeText(xPos,yPos);
return true;
}
public void setBackGroundColor(int randInt){
getWindow().setBackgroundDrawable(new ColorDrawable(randColor[getRandomInt()]));
}
public int getRandomInt(){
Random randomInt = new Random();
randInt = randomInt.nextInt(10);
return randInt;
}
public void changeText(float xPos, float yPos){
textView1.setText("You are at " + xPos + " , " + yPos);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp"
android:text="@string/button" />
Assign an id to your layout:
Then change your code as so:
findViewByID(), like the method name says, needs an ID. Passing off a layout does pass an int, so it compiles fine, but it’s unlikely you’ll match against an id, and the method returnsnull.If anything else also returns null, make sure your layout (and its children views) are contained in the xml file called
activity_main.xmland that you have cleaned your project.