Question

I have defined custom preference class that extends Dialogpreference class for the settings activity,

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

Am using the dialogprefernce to logout a user from the application. So if the user selects 'OK', the sharedprefernces are to be unset and then the user should be directed to the login page.

I tried creating a function in the Activity class and then calling it in this class. Also used Intent class, but the execution stops at

dashboardActivity.startActivity(dashboard);

and generates a Null Pointer exception.

Please help me, to find the solution.

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);
   }
}
Was it helpful?

Solution

use

prefContext.startActivity(dashboard);

instead of

dashboardActivity.startActivity(dashboard);

to access startActivity method. currently you are trying to create instance of DashboardActivity Activity for accessing startActivity method. use prefContext for starting Activity

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top