Search code examples
androidandroid-layoutandroid-linearlayout

NullPointerException when calling setBackground on LinearLayout


I created a Drawable resource file for a LinearLayout background. And I set Drawable in MainActivity using,

Drawable d = getResources().getDrawable(R.drawable.theme_default_bg);
layoutBackground.setBackground(d);

layoutBackground is the LinearLayout. But, when I run this it returns a NullPointerException. How can I solve this?

Edit I set xml background in main.xml file, and it worked. I got this error when i trying to set background from MainActivity.java


Solution

  • I found the mistake. The layout i'm trying to setBackground is in another layout file(activity_main.xml). So i use a LayoutInflater,

    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View mainView = inflater.inflate(R.layout.activity_main, null);
    
    layoutBackground = (LinearLayout)mainView.findViewById(R.id.layout_bg);
    

    Now error solved. I'm sorry guys i wasted your time. I'm really sorry.