-1

I have this onClickListener in onCreate method of my PreferenceActivity, but it gives me error.

Here is the PrefereceActivity:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        Button button = (Button) findViewById(R.id.button2);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
             // do something.
            } 
        });
}

it gives me this error:

unable to start activity componentinfo java.lang.nullpointerexception

any idea what am I doing wrong?

EDIT: My SettingsPreference opens Dialog that holds that "button2".

Rohit Malish
  • 3,209
  • 12
  • 49
  • 67
  • The `Button` is very likely `null`. – Michell Bak Aug 04 '12 at 15:39
  • 1
    First of all, you're not using dialog.xml anywhere. Secondly, you're not setting a content view / layout. You're adding preferences from a resource. Like I said, the error occurs with the Button. You shouldn't need to use Buttons in a PreferenceActivity anyway. – Michell Bak Aug 04 '12 at 15:42
  • My SettingsPreference opens Dialog that holds that "button2". – Rohit Malish Aug 04 '12 at 15:48
  • Read the link in my answer below. There's a perfectly good example including examples with dialogs. What you're doing now is wrong. – Michell Bak Aug 04 '12 at 15:49
  • Edit your question and show us your `settings.xml` file, please. If you have a null pointer exception thats because you do not have any `button2` declared at this xml file, simple as that! – yugidroid Aug 04 '12 at 16:28

1 Answers1

2

The Button is causing your NullPointerException because you haven't set a layout and therefore it is null. You shouldn't need to use buttons in a PreferenceActivity anyway.

There's a perfectly good example of using PreferenceActivity over at the Android developer site: http://developer.android.com/reference/android/preference/PreferenceActivity.html

Michell Bak
  • 13,182
  • 11
  • 64
  • 121