Mario
Mario

Reputation: 14760

DialogFragment attaches to MainActivity instead of parent fragment activity

I create a DialogFragment from a Fragment and I have implemented a listener in the fragment, the problem is that the DialogFragment attaches to MainActivity instead of Parent Frame.

So I have this code in the DialogFragment which is called from the Fragment

// Override the Fragment.onAttach() method to instantiate the
// SensorRateChangeListener
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the SensorRateChangeListener so we can send events to
        // the host
        mListener = (SensorRateChangeListener) activity;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(activity.toString()
                + " must implement SensorRateChangeListener");
    }
}

And this is the code from Fragment which calls the dialog

FragmentTransaction ft = getFragmentManager().beginTransaction();
            Fragment prev = getFragmentManager().findFragmentByTag("dialog");
            if (prev != null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);

            // Create and show the dialog.
            DialogFragment newFragment = SensorRateChangeDlg.newInstance(mStackLevel);
            newFragment.show(ft, "rate");

And when I run the app and the DialogFragment is created it crashes with the error....MainActivity should implement SensorRateChangeListener, but it is implemented in the calling Fragment.

Error: MainActivity@424085b8 must implement SensorRateChangeListener

I cannot implement the SensorRateChangeListener interface in MainActivity, because it have a lot of other functions related to the Fragment and it would make things more complicated.

Upvotes: 0

Views: 623

Answers (1)

Mina Wissa
Mina Wissa

Reputation: 10971

your app crashes here

 mListener = (SensorRateChangeListener) activity;

because it's expecting your Main Activity to be like this:

public class MainAcivity extends Activity implements SensorRateChangeListener{

since you implemented the SensorRateChangeListener interface in another fragment, it crashed. so just implement the SensorRateChangeListener interface in MainActivity or just implement a method like this:

public void setOnSensorRateChangeListener(SensorRateChangeListener listener){
mListener=listener;
}

EDIT

and from the activity/fragment that implements the SensorRateChangeListener interface:

newFragment.setOnSensorRateChangeListener(this);

then check if the listener is not null before calling it:

if(mListener!=null)

Upvotes: 1

Related Questions