Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set listener instance in fragment on application restore

I have created ErrorDialogFragment which contains OnDialogClickListener parameter.

Every other Fragment or Activity that needs to show ErrorDialogFragment sets OnDialogClickListener via public method in ErrorDialogFragment. In the same time, all those activities and fragments implements OnDialogClickListener .

Problem occurs if user exits from application when ErrorDialogFragment is showed, and returns after a while (app is removed from memory). If user clicks on fragment options it will force close, because OnDialogClickListener is not set.

Am i wrong with with activity-listener-fragment pattern, and how do i solve this (application is in beta already.. big pattern change is not acceptable.

Eg:

Interface:

public interface OnDialogClickListener {
    public void OnPositiveClick(int key, Object... args);
    public void OnNegativeClick(int key, Object... args);
}

Activity:

public class Home extends FragmentActivity implements TabListener, ServiceConnection, OnDialogClickListener {
    .
    .
    .
@Override
public void OnPositiveClick(int key, Object... args) {
    //some actions
}

@Override
public void OnNegativeClick(int key, Object... args) {
    //some actions
}

Fragment:

public class ErrorDialogFragment extends DialogFragment implements OnClickListener {

OnDialogClickListener OnDialogClickListener = null;

    .
    .
    .

public void setDialogListener(OnDialogClickListener listener)
{   
    OnDialogClickListener = listener;
}

@Override
public void onClick(DialogInterface dialog, int which) {    
    if(OnDialogClickListener != null){
        switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                this.dismiss();
                OnDialogClickListener.OnPositiveClick(KEY, args);
                break;
            default:
                this.dismiss();
                OnDialogClickListener.OnNegativeClick(KEY, args);
                break;
        }
    }
    else
        this.dismiss();
}    
like image 286
bajicdusko Avatar asked Feb 12 '23 17:02

bajicdusko


1 Answers

You're way off better setting it in DialogFragment#onAttach(Activity) callback like this:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try { 
        mOnDialogClickListener = (OnDialogClickListener) activity;
    } catch(ClassCastException e) {
        throw new ClassCastException(activity.toString() + "must implement" + OnDialogClickListener.class.getSimpleName());
    }
}

@Override
public void onDetach() {
    super.onDetach()
    mOnDialogClickListener = null;
}

And finally, obviously, make your Activity implements OnDialogClickListener

like image 188
Christopher Francisco Avatar answered Feb 15 '23 11:02

Christopher Francisco