Search code examples
javaandroidbackgrounddrawablesetbackground

Background Change gives Force Close


I just made a little code to make my Background change to a Drawable if the Checkbox in my Preferences is checked, and make it go white when it isn't. The code works fine in my MainActivity, but it gives a NullPointerException in another Activity (LinksActivity). Can anyone possibly correct me on this?

package nl.plplpl.ccs;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.LinearLayout;


public class LinksActivity extends Activity {

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

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
protected void onResume() {
    LinearLayout linkslayout = (LinearLayout) findViewById(R.id.linkslayout);
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    Boolean bg = prefs.getBoolean("background", false);
    if (bg){

        if (Build.VERSION.SDK_INT >= 16)
            linkslayout.setBackground(getResources().getDrawable(R.drawable.background));
        else
            linkslayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.background));
    } else {
        linkslayout.setBackgroundResource(R.color.white);
    }
    super.onResume();
    }
}

Solution

  • You forgot to set the activity content.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
    }