setBackground null pointer exception

596 views Asked by At

im trying to set background to my activity but it throws nullpointer exception everytime

here is my code

 super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    RelativeLayout layout  = (RelativeLayout) findViewById(R.layout.activity_main);
    layout.setBackground(getResources().getDrawable(R.drawable.welcome_2));
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            layout.setBackgroundDrawable( getResources().getDrawable(R.drawable.welcome_1) );
            } else { 
                layout.setBackground(getResources().getDrawable(R.drawable.welcome));
            } 
setContentView(R.layout.activity_main);

and this is my layout

<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" >
2

There are 2 answers

0
M D On BEST ANSWER

move

 setContentView(R.layout.activity_main);

before

 RelativeLayout layout  = (RelativeLayout) findViewById(R.id.layout);

and defined relativelayout Id in XML

<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"
 android:id="@+id/layout"
 tools:context=".MainActivity" >
0
Rishi Paul On

Firstly Give id to Layout in Xml

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

Then Inside java Code Use like this

 setContentView(R.layout.activity_main);
 RelativeLayout layout  = (RelativeLayout) findViewById(R.id.layout);
 layout.setBackground(R.drawable.welcome_2);