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

时间:2013-03-28 12:28:24

标签: android android-activity dialog-preference

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

的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);
}

使用dialogprefernce从应用程序注销用户。因此,如果用户选择“确定”,则取消设置共享首选项,然后将用户定向到登录页面。

我尝试在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);
   }
}

1 个答案:

答案 0 :(得分:1)

使用

prefContext.startActivity(dashboard);

而不是

dashboardActivity.startActivity(dashboard);

访问startActivity方法。目前您正在尝试创建DashboardActivity活动的实例以访问startActivity方法。使用prefContext启动活动