Android Start Preference Activity Intent导致Exception

时间:2011-07-03 19:54:58

标签: android

我遇到了问题,我想运行一个处理偏好对话框的活动

Intent i= new Intent(getBaseContext(), PreferencesActivity.class);
            startActivity(i);

当我运行应用程序时,我只会在活动开始时获得nullpointerexcepltion。怎么了?

PreferencesActivity看起来就是这样:

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;

public class PreferencesActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.preferences);
        // Get the custom preference
        Preference customPref = (Preference) findPreference("customPref");
        customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

             public boolean onPreferenceClick(Preference preference) {
                 Toast.makeText(getBaseContext(),
                     "The custom preference has been clicked",
                     Toast.LENGTH_LONG).show();
                 SharedPreferences customSharedPreference = getSharedPreferences(
                     "myCustomSharedPrefs", Activity.MODE_PRIVATE);
                 SharedPreferences.Editor editor = customSharedPreference.edit();
                 editor.putString("myCustomPref","The preference has been clicked");
                 editor.commit();
                 return true;
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

问题出在getBaseContext()中。如果使用此方法,则应通过构造函数或“setBaseContext”方法设置上下文。您可以尝试使用“getApplicationContext”,或只使用“this”

答案 1 :(得分:0)

尝试以下方法......

public boolean onPreferenceClick(Preference preference) {

    // Use PreferencesActivity.this for the Context used in the Toast below...
    Toast.makeText(PreferencesActivity.this,
        "The custom preference has been clicked",
        Toast.LENGTH_LONG).show();

    // Use Context.MODE_PRIVATE instead of Activity.MODE_PRIVATE
    SharedPreferences customSharedPreference = getSharedPreferences(
        "myCustomSharedPrefs", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = customSharedPreference.edit();
    editor.putString("myCustomPref","The preference has been clicked");
    editor.commit();
    return true;
}