C
C
coden552015-12-22 19:58:45
Android
coden55, 2015-12-22 19:58:45

Confused about contexts (Fragment, AlertDialog, callback interface)?

Code below, dialog does not call ((ResultListener) context).onSpinnerSelectResult(keys[selecteditemid]); , error java.lang.ClassCastException: ru........android.Activity_Main cannot be cast to ru.............android.Dialog_SpinnerSelect$ResultListener . Already broke my head how to please the program, help :)

public class Fragment_Layers extends Fragment implements Dialog_SpinnerSelect.ResultListener {
......
    void openDialog() {
        Dialog_SpinnerSelect dialog = new Dialog_SpinnerSelect(getActivity());
        dialog.show();
    }

    @Override
    public void onSpinnerSelectResult(Integer result) {
        //todo 
    }
}

public class Dialog_SpinnerSelect {

    private Context context;

    public Dialog_SpinnerSelect(Context context) {
        this.context = context;
        builder = new AlertDialog.Builder(context);
}

   public void show() {
        ......
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
                ((ResultListener) context).onSpinnerSelectResult(keys[selecteditemid]);
            }
        });
.......        
dialog.show();
    }

    public interface ResultListener {
        void onSpinnerSelectResult(Integer result);
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Lebedev, 2015-12-23
@coden55

You are not confused in contexts, you do not understand what parameters you pass to constructors. I advise you to study Java more carefully.
Replace

Dialog_SpinnerSelect dialog = new Dialog_SpinnerSelect(getActivity());
on the
Dialog_SpinnerSelect dialog = new Dialog_SpinnerSelect(this);
;
private Context context;

public Dialog_SpinnerSelect(Context context) {
        this.context = context;
        builder = new AlertDialog.Builder(context);
}
on the
private Fragment_Layers fragment;

public Dialog_SpinnerSelect(Fragment_Layers fragment) {
        this.fragment = fragment;
        builder = new AlertDialog.Builder(fragment.getActivity());
}
;
public void onClick(DialogInterface dialog, int arg1) {
                ((ResultListener) context).onSpinnerSelectResult(keys[selecteditemid]);
            }
on the
public void onClick(DialogInterface dialog, int arg1) {
                ((ResultListener) fragment).onSpinnerSelectResult(keys[selecteditemid]);
            }

F
FoxInSox, 2015-12-22
@FoxInSox

context cannot become a ResultListener. Read how to write in Java first, and then try to do something for Android.

H
Hakito, 2015-12-22
@hakito

As I understand it, your MainActivity does not implement the OnResultListener interface. Here from the error itself everything is clear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question