Home » Android » dialog – Problems with alertdialog show in fragment android

dialog – Problems with alertdialog show in fragment android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have followed android example but I have an incomprehensive error :

void showDialog() {
    DialogFragment newFragment = MyAlertDialogFragment.newInstance();
    newFragment.show(fm, "alert");
}

public static class MyAlertDialogFragment extends DialogFragment {
    public static MyAlertDialogFragment newInstance() {
        MyAlertDialogFragment frag = new MyAlertDialogFragment();
        return frag;
    }

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity()).setTitle("test")
                .setMessage("bla bla bla").create();
    }
}

newFragment.show(fm, "alert"); returns me an error :

The method show(FragmentManager, String) in the type DialogFragment is
not applicable for the arguments (FragmentManager, String)

Someone could help me ?

How to&Answers:

The problem is because you need to be using the support package’s FragmentManager but you are using the native FragmentManager when you call getFragmentManager(). Try calling getSupportFragmentManager() when initializing your variable fm.

Answer:

Actually after you do as @Jacob says, you also have to make sure that you include DialogFragment from the Support package and not from the native package.

You can do that by importing,

import android.support.v4.app.DialogFragment;

Answer:

In my case my minSDK is set to 14 so I did not want to use the support package. My problem was I was importing the wrong DialogFragment like so:

import android.support.v4.app.DialogFragment;

I changed it to this and it worked:

import android.app.DialogFragment;