Quick question

0 Kenneth Malicay · June 24, 2015
Why do I get a null pointer exception? (on comment)

--- Java

public class MainActivity extends Activity {
RelativeLayout layout;

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

initialize();

setContentView(R.layout.activity_main);
}

public void initialize() {
layout = (RelativeLayout) findViewById(R.id.layout);
layout.setBackgroundColor(Color.GRAY); // Why do I get null pointer exception here?
}
}

--- XML


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/layout">

</RelativeLayout>




I just want to know why do I get null exception. Thanks!

Post a Reply

Replies

Oldest  Newest  Rating
0 Kenneth Malicay · June 24, 2015
FIXED: by switching initialize() and setContentView().

So that means the R.id.layout is null before setContentView I guess. Correct me if I'm wrong.
  • 1

Java / Android Development

107,013 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator