Android 如何从DialogPreference类中的onDialogClosed方法返回主活动

Android 如何从DialogPreference类中的onDialogClosed方法返回主活动,android,android-activity,dialog-preference,Android,Android Activity,Dialog Preference,我已经定义了自定义首选项类,该类扩展了设置活动的Dialogpreference类 public class YesNoPreference extends DialogPreference { private boolean mWasPositiveResult; DashboardActivity dashboardActivity; Context prefContext; public YesNoPreference(Context context, AttributeSet

我已经定义了自定义首选项类,该类扩展了设置活动的Dialogpreference类

public class YesNoPreference extends DialogPreference {

private boolean mWasPositiveResult;
    DashboardActivity dashboardActivity;
Context prefContext;

public YesNoPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    userSession = new UserSessions(context);
    prefContext = context;
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

    if (callChangeListener(positiveResult)) {
        setValue(positiveResult);

        /* Unset all user shared preferences */
        userSession.unsetSessionData();

    try {   
    dashboardActivity = new DashboardActivity();
    //dashboardActivity.loginScreen();
    Intent dashboard = new Intent(prefContext, DashboardActivity.class);
    dashboardActivity.startActivity(dashboard);

     } catch (Exception e) {
     e.printStackTrace();
     }
    }
}

/**
 * Sets the value of this preference, and saves it to the persistent store
 * if required.
 * 
 * @param value The value of the preference.
 */
public void setValue(boolean value) {
    mWasPositiveResult = value;

    persistBoolean(value);

    notifyDependencyChange(!value);
}
我使用对话框Preference从应用程序注销用户。因此,如果用户选择“确定”,共享引用将被取消设置,然后用户将被引导到登录页面

我尝试在Activity类中创建一个函数,然后在此类中调用它。也使用了Intent类,但执行在

dashboardActivity.startActivity(dashboard);
并生成空指针异常

请帮我找到解决办法

public class SettingsActivity extends Activity {

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

    // Display the fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
   }

}

public class SettingsFragment extends PreferenceFragment {

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

       // Load the preferences from an XML resource
       addPreferencesFromResource(R.xml.pref_settings);
   }
}
使用

而不是

dashboardActivity.startActivity(dashboard);

访问
startActivity
方法。当前,您正在尝试创建
仪表板活动
活动的实例,以访问
startActivity
方法。使用
prefContext
开始活动

非常感谢。。。成功了。你能帮我理解为什么我们必须使用上下文对象而不是活动对象吗??谢谢你advance@Mamta:您将获得
NullPointerexception
,因为活动与普通java类不同。像在java中一样,我们创建一个对象来访问类中的任何方法。如果“活动”未运行(如仪表板活动未运行),则在此之前切勿尝试创建“活动”对象。请始终抛出
NullPointerexception
dashboardActivity.startActivity(dashboard);