Can AlertDialog be made to work when called from a Fragment?How to prevent a dialog from closing when a button is clickedonActivityResult is not being called in FragmentHow to determine when Fragment becomes visible in ViewPagerDialogFragment throws ClassCastException if called from FragmentWeird black line above DialogFragment AlertDialogDilemma: when to use Fragments vs Activities:Finding a textView from XML of a Custom View for a AlertDialog FragmentDoes opening an activity from a dialog fragment dismisses the dialog fragment?Error TimePickerDialog. Here is the code:Unable to initialize the Context

When did J.K. Rowling decide to make Ron and Hermione a couple?

How did Biff return to 2015 from 1955 without a lightning strike?

Matrix condition number and reordering

Does the problem of P vs NP come under the category of Operational Research?

Map vs. Table for index-specific operations on 2D arrays

Reasons for using monsters as bioweapons

How to determine if result of process substitution is a file path

What is Albrecht Dürer's Perspective Machine drawing style?

How to power down external drive safely

Why have both: BJT and FET transistors on IC output?

Overprovisioning SSD on ubuntu. How? Ubuntu 19.04 Samsung SSD 860

Why are Star Wars Rebel Alliance ships named after letters from the Latin alphabet?

What is the most 'environmentally friendly' way to learn to fly?

What is the difference between 2/4 and 4/4 when it comes the accented beats?

Export economy of Mars

Why are sugars in whole fruits not digested the same way sugars in juice are?

δόλος = deceit in John 1:47

Password management for kids - what's a good way to start?

How do people drown while wearing a life jacket?

Has J.J.Jameson ever found out that Peter Parker is Spider-Man?

Being told my "network" isn't PCI compliant. I don't even have a server! Do I have to comply?

A conjectural trigonometric identity

What's the term for a group of people who enjoy literary works?

linearization of objective function



Can AlertDialog be made to work when called from a Fragment?


How to prevent a dialog from closing when a button is clickedonActivityResult is not being called in FragmentHow to determine when Fragment becomes visible in ViewPagerDialogFragment throws ClassCastException if called from FragmentWeird black line above DialogFragment AlertDialogDilemma: when to use Fragments vs Activities:Finding a textView from XML of a Custom View for a AlertDialog FragmentDoes opening an activity from a dialog fragment dismisses the dialog fragment?Error TimePickerDialog. Here is the code:Unable to initialize the Context






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have an AlertDialog that works fine with Activites, but it doesn't work with Fragments due to AlertDialog.Builder(getActivity). In this case, a parent Activity holds a child Fragment that uses a RecyclerView to display records. When the user swipes a record, an AlertDialog is displayed to confirm the deletion. However, this doesn't work as the AlertDialog references the parent Activity. I have included the AlertDialog's code and the LogCat output from the AlertFragment's code below.



I instantiate the ConfirmDialogFragment in the child Fragment as follows:



DialogFragment confirmDialog = new ConfirmDialogFragment();
confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


The AlertDialog Fragment code is shown below:



package com.example.jbiss.petminder.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.DialogFragment;
import com.example.jbiss.petminder.R;
import java.util.Set;

public class ConfirmDialogFragment extends DialogFragment
private static final String TAG = "ConfirmDialogFragment";
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
Log.d(TAG, "Entered onCreateDialog");
if(savedInstanceState ==null)
Log.d(TAG, "savedInstanceState is null");
else
Set<String> s = savedInstanceState.keySet();
Log.d(TAG, "savedInstanceState is: " + s);

Log.d(TAG, "getParentFragment is: " + getParentFragment());
Log.d(TAG, "getContext is: " + getContext());
Log.d(TAG, "getActivity is: " + getActivity());
Log.d(TAG, "this is: " + this);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.delete_confirm)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int id)
Log.d(TAG, "Delete clicked");
Log.d(TAG, "getContext is: " + getContext());
Log.d(TAG, "this is: " + this);
mListener.onDialogPositiveClick(ConfirmDialogFragment.this);

)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int id)
// User cancelled the dialog
Log.d(TAG, "Cancel clicked");
mListener.onDialogNegativeClick(ConfirmDialogFragment.this);

);
return builder.create();


public interface ConfirmDialogListener
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);


// Use this instance of the interface to deliver action events
ConfirmDialogListener mListener;

// Override the Fragment.onAttach() method to instantiate the ConfirmDialogListener
@Override
public void onAttach(Context context)
super.onAttach(context);
Log.d(TAG, "Entered onAttach");
// Verify that the host activity implements the callback interface
try
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (ConfirmDialogListener) context;
Log.d(TAG, "activity is: " + context);
Log.d(TAG, "mListener is: " + mListener);
catch (ClassCastException e)
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement NoticeDialogListener");





The LogCat output shown in the code is shown below.



MedicalInformationFragment: swiped to the 4!
MedicalInformationFragment: position swiped is: 0
ConfirmDialogFragment: Entered onAttach
ConfirmDialogFragment: activity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
ConfirmDialogFragment: mListener is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
ConfirmDialogFragment: Entered onCreateDialog
ConfirmDialogFragment: savedInstanceState is null
ConfirmDialogFragment: getParentFragment is: null
ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
ConfirmDialogFragment: getActivity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
ConfirmDialogFragment: this is: ConfirmDialogFragmenta4e01a0 #2 ConfirmDialogFragment


When ConfirmDialogFragment's Delete is clicked, LogCat displays the following:



ConfirmDialogFragment: Delete clicked
ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
ConfirmDialogFragment: this is: com.example.jbiss.petminder.dialogs.ConfirmDialogFragment$2@c3512d0
PetInformationActivity: Entered onDialogPositiveClick
PetInformationViewModel: Entered: deletePetName


As can be see in the LogCat output, ConfirmDialogFragment does return to the calling Fragment's ConfirmDialogFragment.ConfirmDialogListener Interface methods, it goes to the parent Activity's.



This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's. As can be seen in the LogCat output, trying to use getContext also references the parent Activity. All questions about using AlertDialog state that getActivity is to be used as they seem to be about using the DialogFragment, not about a Fragment calling it.



Is AlertDialog intended to be used from a Fragment? Is there a Fragment's equivalent to an Activity's reference that can be passed to the AlertDialog's constructor as shown below?



DialogFragment confirmDialog = new ConfirmDialogFragment(CallingFragmentReferenceSimilarToAnActivity);
confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


I should be able to overload the AlertDialog's constructor in that case, I believe.










share|improve this question
































    0















    I have an AlertDialog that works fine with Activites, but it doesn't work with Fragments due to AlertDialog.Builder(getActivity). In this case, a parent Activity holds a child Fragment that uses a RecyclerView to display records. When the user swipes a record, an AlertDialog is displayed to confirm the deletion. However, this doesn't work as the AlertDialog references the parent Activity. I have included the AlertDialog's code and the LogCat output from the AlertFragment's code below.



    I instantiate the ConfirmDialogFragment in the child Fragment as follows:



    DialogFragment confirmDialog = new ConfirmDialogFragment();
    confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


    The AlertDialog Fragment code is shown below:



    package com.example.jbiss.petminder.dialogs;

    import android.app.AlertDialog;
    import android.app.Dialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.util.Log;
    import androidx.fragment.app.DialogFragment;
    import com.example.jbiss.petminder.R;
    import java.util.Set;

    public class ConfirmDialogFragment extends DialogFragment
    private static final String TAG = "ConfirmDialogFragment";
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    Log.d(TAG, "Entered onCreateDialog");
    if(savedInstanceState ==null)
    Log.d(TAG, "savedInstanceState is null");
    else
    Set<String> s = savedInstanceState.keySet();
    Log.d(TAG, "savedInstanceState is: " + s);

    Log.d(TAG, "getParentFragment is: " + getParentFragment());
    Log.d(TAG, "getContext is: " + getContext());
    Log.d(TAG, "getActivity is: " + getActivity());
    Log.d(TAG, "this is: " + this);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(R.string.delete_confirm)
    .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener()
    public void onClick(DialogInterface dialog, int id)
    Log.d(TAG, "Delete clicked");
    Log.d(TAG, "getContext is: " + getContext());
    Log.d(TAG, "this is: " + this);
    mListener.onDialogPositiveClick(ConfirmDialogFragment.this);

    )
    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
    public void onClick(DialogInterface dialog, int id)
    // User cancelled the dialog
    Log.d(TAG, "Cancel clicked");
    mListener.onDialogNegativeClick(ConfirmDialogFragment.this);

    );
    return builder.create();


    public interface ConfirmDialogListener
    public void onDialogPositiveClick(DialogFragment dialog);
    public void onDialogNegativeClick(DialogFragment dialog);


    // Use this instance of the interface to deliver action events
    ConfirmDialogListener mListener;

    // Override the Fragment.onAttach() method to instantiate the ConfirmDialogListener
    @Override
    public void onAttach(Context context)
    super.onAttach(context);
    Log.d(TAG, "Entered onAttach");
    // Verify that the host activity implements the callback interface
    try
    // Instantiate the NoticeDialogListener so we can send events to the host
    mListener = (ConfirmDialogListener) context;
    Log.d(TAG, "activity is: " + context);
    Log.d(TAG, "mListener is: " + mListener);
    catch (ClassCastException e)
    // The activity doesn't implement the interface, throw exception
    throw new ClassCastException(context.toString()
    + " must implement NoticeDialogListener");





    The LogCat output shown in the code is shown below.



    MedicalInformationFragment: swiped to the 4!
    MedicalInformationFragment: position swiped is: 0
    ConfirmDialogFragment: Entered onAttach
    ConfirmDialogFragment: activity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
    ConfirmDialogFragment: mListener is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
    ConfirmDialogFragment: Entered onCreateDialog
    ConfirmDialogFragment: savedInstanceState is null
    ConfirmDialogFragment: getParentFragment is: null
    ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
    ConfirmDialogFragment: getActivity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
    ConfirmDialogFragment: this is: ConfirmDialogFragmenta4e01a0 #2 ConfirmDialogFragment


    When ConfirmDialogFragment's Delete is clicked, LogCat displays the following:



    ConfirmDialogFragment: Delete clicked
    ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
    ConfirmDialogFragment: this is: com.example.jbiss.petminder.dialogs.ConfirmDialogFragment$2@c3512d0
    PetInformationActivity: Entered onDialogPositiveClick
    PetInformationViewModel: Entered: deletePetName


    As can be see in the LogCat output, ConfirmDialogFragment does return to the calling Fragment's ConfirmDialogFragment.ConfirmDialogListener Interface methods, it goes to the parent Activity's.



    This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's. As can be seen in the LogCat output, trying to use getContext also references the parent Activity. All questions about using AlertDialog state that getActivity is to be used as they seem to be about using the DialogFragment, not about a Fragment calling it.



    Is AlertDialog intended to be used from a Fragment? Is there a Fragment's equivalent to an Activity's reference that can be passed to the AlertDialog's constructor as shown below?



    DialogFragment confirmDialog = new ConfirmDialogFragment(CallingFragmentReferenceSimilarToAnActivity);
    confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


    I should be able to overload the AlertDialog's constructor in that case, I believe.










    share|improve this question




























      0












      0








      0








      I have an AlertDialog that works fine with Activites, but it doesn't work with Fragments due to AlertDialog.Builder(getActivity). In this case, a parent Activity holds a child Fragment that uses a RecyclerView to display records. When the user swipes a record, an AlertDialog is displayed to confirm the deletion. However, this doesn't work as the AlertDialog references the parent Activity. I have included the AlertDialog's code and the LogCat output from the AlertFragment's code below.



      I instantiate the ConfirmDialogFragment in the child Fragment as follows:



      DialogFragment confirmDialog = new ConfirmDialogFragment();
      confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


      The AlertDialog Fragment code is shown below:



      package com.example.jbiss.petminder.dialogs;

      import android.app.AlertDialog;
      import android.app.Dialog;
      import android.content.Context;
      import android.content.DialogInterface;
      import android.os.Bundle;
      import android.util.Log;
      import androidx.fragment.app.DialogFragment;
      import com.example.jbiss.petminder.R;
      import java.util.Set;

      public class ConfirmDialogFragment extends DialogFragment
      private static final String TAG = "ConfirmDialogFragment";
      @Override
      public Dialog onCreateDialog(Bundle savedInstanceState)
      Log.d(TAG, "Entered onCreateDialog");
      if(savedInstanceState ==null)
      Log.d(TAG, "savedInstanceState is null");
      else
      Set<String> s = savedInstanceState.keySet();
      Log.d(TAG, "savedInstanceState is: " + s);

      Log.d(TAG, "getParentFragment is: " + getParentFragment());
      Log.d(TAG, "getContext is: " + getContext());
      Log.d(TAG, "getActivity is: " + getActivity());
      Log.d(TAG, "this is: " + this);
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setMessage(R.string.delete_confirm)
      .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener()
      public void onClick(DialogInterface dialog, int id)
      Log.d(TAG, "Delete clicked");
      Log.d(TAG, "getContext is: " + getContext());
      Log.d(TAG, "this is: " + this);
      mListener.onDialogPositiveClick(ConfirmDialogFragment.this);

      )
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
      public void onClick(DialogInterface dialog, int id)
      // User cancelled the dialog
      Log.d(TAG, "Cancel clicked");
      mListener.onDialogNegativeClick(ConfirmDialogFragment.this);

      );
      return builder.create();


      public interface ConfirmDialogListener
      public void onDialogPositiveClick(DialogFragment dialog);
      public void onDialogNegativeClick(DialogFragment dialog);


      // Use this instance of the interface to deliver action events
      ConfirmDialogListener mListener;

      // Override the Fragment.onAttach() method to instantiate the ConfirmDialogListener
      @Override
      public void onAttach(Context context)
      super.onAttach(context);
      Log.d(TAG, "Entered onAttach");
      // Verify that the host activity implements the callback interface
      try
      // Instantiate the NoticeDialogListener so we can send events to the host
      mListener = (ConfirmDialogListener) context;
      Log.d(TAG, "activity is: " + context);
      Log.d(TAG, "mListener is: " + mListener);
      catch (ClassCastException e)
      // The activity doesn't implement the interface, throw exception
      throw new ClassCastException(context.toString()
      + " must implement NoticeDialogListener");





      The LogCat output shown in the code is shown below.



      MedicalInformationFragment: swiped to the 4!
      MedicalInformationFragment: position swiped is: 0
      ConfirmDialogFragment: Entered onAttach
      ConfirmDialogFragment: activity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: mListener is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: Entered onCreateDialog
      ConfirmDialogFragment: savedInstanceState is null
      ConfirmDialogFragment: getParentFragment is: null
      ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: getActivity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: this is: ConfirmDialogFragmenta4e01a0 #2 ConfirmDialogFragment


      When ConfirmDialogFragment's Delete is clicked, LogCat displays the following:



      ConfirmDialogFragment: Delete clicked
      ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: this is: com.example.jbiss.petminder.dialogs.ConfirmDialogFragment$2@c3512d0
      PetInformationActivity: Entered onDialogPositiveClick
      PetInformationViewModel: Entered: deletePetName


      As can be see in the LogCat output, ConfirmDialogFragment does return to the calling Fragment's ConfirmDialogFragment.ConfirmDialogListener Interface methods, it goes to the parent Activity's.



      This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's. As can be seen in the LogCat output, trying to use getContext also references the parent Activity. All questions about using AlertDialog state that getActivity is to be used as they seem to be about using the DialogFragment, not about a Fragment calling it.



      Is AlertDialog intended to be used from a Fragment? Is there a Fragment's equivalent to an Activity's reference that can be passed to the AlertDialog's constructor as shown below?



      DialogFragment confirmDialog = new ConfirmDialogFragment(CallingFragmentReferenceSimilarToAnActivity);
      confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


      I should be able to overload the AlertDialog's constructor in that case, I believe.










      share|improve this question
















      I have an AlertDialog that works fine with Activites, but it doesn't work with Fragments due to AlertDialog.Builder(getActivity). In this case, a parent Activity holds a child Fragment that uses a RecyclerView to display records. When the user swipes a record, an AlertDialog is displayed to confirm the deletion. However, this doesn't work as the AlertDialog references the parent Activity. I have included the AlertDialog's code and the LogCat output from the AlertFragment's code below.



      I instantiate the ConfirmDialogFragment in the child Fragment as follows:



      DialogFragment confirmDialog = new ConfirmDialogFragment();
      confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


      The AlertDialog Fragment code is shown below:



      package com.example.jbiss.petminder.dialogs;

      import android.app.AlertDialog;
      import android.app.Dialog;
      import android.content.Context;
      import android.content.DialogInterface;
      import android.os.Bundle;
      import android.util.Log;
      import androidx.fragment.app.DialogFragment;
      import com.example.jbiss.petminder.R;
      import java.util.Set;

      public class ConfirmDialogFragment extends DialogFragment
      private static final String TAG = "ConfirmDialogFragment";
      @Override
      public Dialog onCreateDialog(Bundle savedInstanceState)
      Log.d(TAG, "Entered onCreateDialog");
      if(savedInstanceState ==null)
      Log.d(TAG, "savedInstanceState is null");
      else
      Set<String> s = savedInstanceState.keySet();
      Log.d(TAG, "savedInstanceState is: " + s);

      Log.d(TAG, "getParentFragment is: " + getParentFragment());
      Log.d(TAG, "getContext is: " + getContext());
      Log.d(TAG, "getActivity is: " + getActivity());
      Log.d(TAG, "this is: " + this);
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setMessage(R.string.delete_confirm)
      .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener()
      public void onClick(DialogInterface dialog, int id)
      Log.d(TAG, "Delete clicked");
      Log.d(TAG, "getContext is: " + getContext());
      Log.d(TAG, "this is: " + this);
      mListener.onDialogPositiveClick(ConfirmDialogFragment.this);

      )
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
      public void onClick(DialogInterface dialog, int id)
      // User cancelled the dialog
      Log.d(TAG, "Cancel clicked");
      mListener.onDialogNegativeClick(ConfirmDialogFragment.this);

      );
      return builder.create();


      public interface ConfirmDialogListener
      public void onDialogPositiveClick(DialogFragment dialog);
      public void onDialogNegativeClick(DialogFragment dialog);


      // Use this instance of the interface to deliver action events
      ConfirmDialogListener mListener;

      // Override the Fragment.onAttach() method to instantiate the ConfirmDialogListener
      @Override
      public void onAttach(Context context)
      super.onAttach(context);
      Log.d(TAG, "Entered onAttach");
      // Verify that the host activity implements the callback interface
      try
      // Instantiate the NoticeDialogListener so we can send events to the host
      mListener = (ConfirmDialogListener) context;
      Log.d(TAG, "activity is: " + context);
      Log.d(TAG, "mListener is: " + mListener);
      catch (ClassCastException e)
      // The activity doesn't implement the interface, throw exception
      throw new ClassCastException(context.toString()
      + " must implement NoticeDialogListener");





      The LogCat output shown in the code is shown below.



      MedicalInformationFragment: swiped to the 4!
      MedicalInformationFragment: position swiped is: 0
      ConfirmDialogFragment: Entered onAttach
      ConfirmDialogFragment: activity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: mListener is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: Entered onCreateDialog
      ConfirmDialogFragment: savedInstanceState is null
      ConfirmDialogFragment: getParentFragment is: null
      ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: getActivity is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: this is: ConfirmDialogFragmenta4e01a0 #2 ConfirmDialogFragment


      When ConfirmDialogFragment's Delete is clicked, LogCat displays the following:



      ConfirmDialogFragment: Delete clicked
      ConfirmDialogFragment: getContext is: com.example.jbiss.petminder.activities.PetInformationActivity@8963dda
      ConfirmDialogFragment: this is: com.example.jbiss.petminder.dialogs.ConfirmDialogFragment$2@c3512d0
      PetInformationActivity: Entered onDialogPositiveClick
      PetInformationViewModel: Entered: deletePetName


      As can be see in the LogCat output, ConfirmDialogFragment does return to the calling Fragment's ConfirmDialogFragment.ConfirmDialogListener Interface methods, it goes to the parent Activity's.



      This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's. As can be seen in the LogCat output, trying to use getContext also references the parent Activity. All questions about using AlertDialog state that getActivity is to be used as they seem to be about using the DialogFragment, not about a Fragment calling it.



      Is AlertDialog intended to be used from a Fragment? Is there a Fragment's equivalent to an Activity's reference that can be passed to the AlertDialog's constructor as shown below?



      DialogFragment confirmDialog = new ConfirmDialogFragment(CallingFragmentReferenceSimilarToAnActivity);
      confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");


      I should be able to overload the AlertDialog's constructor in that case, I believe.







      android android-alertdialog android-dialogfragment






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 5:31









      Vishrut Mavani

      1,4848 silver badges23 bronze badges




      1,4848 silver badges23 bronze badges










      asked Mar 27 at 0:28









      JeffJeff

      909 bronze badges




      909 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1















          This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's.




          The issue is not with the AlertDialog but with how your listener is set. Since Fragment's getContext() method returns context of the parent Activity.



          mListener = (ConfirmDialogListener) context;


          This line sets your listener to be the parent Activity of the calling Fragment. Instead of setting mListener to the parent activity, you have to set it to the calling fragment.



          First, you have to set the target fragment for your DialogFragment while instantiating.



          DialogFragment confirmDialog = new ConfirmDialogFragment();
          confirmDialog.setTargetFragment(this, "CONFIRM_DIALOG_TAG");
          if (getFragmentManager() != null)
          confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");



          Now, inside your dialog fragment's onCreate, you can set the callback to be your fragment.



          try 
          mListener = (ConfirmDialogListener) getTargetFragment();
          catch (ClassCastException e)
          throw new ClassCastException(context.toString()
          + " must implement ConfirmDialogListener");



          And remove the code from onAttach method.






          share|improve this answer



























          • Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

            – Jeff
            Mar 27 at 22:46











          • Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

            – Jeff
            Mar 27 at 23:54












          • I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

            – Ranjan
            Mar 28 at 5:09











          • Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

            – Jeff
            Mar 28 at 23:47






          • 1





            It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

            – Jeff
            Mar 29 at 13:32










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55368094%2fcan-alertdialog-be-made-to-work-when-called-from-a-fragment%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1















          This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's.




          The issue is not with the AlertDialog but with how your listener is set. Since Fragment's getContext() method returns context of the parent Activity.



          mListener = (ConfirmDialogListener) context;


          This line sets your listener to be the parent Activity of the calling Fragment. Instead of setting mListener to the parent activity, you have to set it to the calling fragment.



          First, you have to set the target fragment for your DialogFragment while instantiating.



          DialogFragment confirmDialog = new ConfirmDialogFragment();
          confirmDialog.setTargetFragment(this, "CONFIRM_DIALOG_TAG");
          if (getFragmentManager() != null)
          confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");



          Now, inside your dialog fragment's onCreate, you can set the callback to be your fragment.



          try 
          mListener = (ConfirmDialogListener) getTargetFragment();
          catch (ClassCastException e)
          throw new ClassCastException(context.toString()
          + " must implement ConfirmDialogListener");



          And remove the code from onAttach method.






          share|improve this answer



























          • Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

            – Jeff
            Mar 27 at 22:46











          • Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

            – Jeff
            Mar 27 at 23:54












          • I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

            – Ranjan
            Mar 28 at 5:09











          • Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

            – Jeff
            Mar 28 at 23:47






          • 1





            It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

            – Jeff
            Mar 29 at 13:32















          1















          This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's.




          The issue is not with the AlertDialog but with how your listener is set. Since Fragment's getContext() method returns context of the parent Activity.



          mListener = (ConfirmDialogListener) context;


          This line sets your listener to be the parent Activity of the calling Fragment. Instead of setting mListener to the parent activity, you have to set it to the calling fragment.



          First, you have to set the target fragment for your DialogFragment while instantiating.



          DialogFragment confirmDialog = new ConfirmDialogFragment();
          confirmDialog.setTargetFragment(this, "CONFIRM_DIALOG_TAG");
          if (getFragmentManager() != null)
          confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");



          Now, inside your dialog fragment's onCreate, you can set the callback to be your fragment.



          try 
          mListener = (ConfirmDialogListener) getTargetFragment();
          catch (ClassCastException e)
          throw new ClassCastException(context.toString()
          + " must implement ConfirmDialogListener");



          And remove the code from onAttach method.






          share|improve this answer



























          • Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

            – Jeff
            Mar 27 at 22:46











          • Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

            – Jeff
            Mar 27 at 23:54












          • I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

            – Ranjan
            Mar 28 at 5:09











          • Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

            – Jeff
            Mar 28 at 23:47






          • 1





            It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

            – Jeff
            Mar 29 at 13:32













          1












          1








          1








          This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's.




          The issue is not with the AlertDialog but with how your listener is set. Since Fragment's getContext() method returns context of the parent Activity.



          mListener = (ConfirmDialogListener) context;


          This line sets your listener to be the parent Activity of the calling Fragment. Instead of setting mListener to the parent activity, you have to set it to the calling fragment.



          First, you have to set the target fragment for your DialogFragment while instantiating.



          DialogFragment confirmDialog = new ConfirmDialogFragment();
          confirmDialog.setTargetFragment(this, "CONFIRM_DIALOG_TAG");
          if (getFragmentManager() != null)
          confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");



          Now, inside your dialog fragment's onCreate, you can set the callback to be your fragment.



          try 
          mListener = (ConfirmDialogListener) getTargetFragment();
          catch (ClassCastException e)
          throw new ClassCastException(context.toString()
          + " must implement ConfirmDialogListener");



          And remove the code from onAttach method.






          share|improve this answer
















          This is due to the fact that AlertDialog.Builder is instantiated with getActivity() that gets the parent Activity's reference, NOT the calling Fragment's.




          The issue is not with the AlertDialog but with how your listener is set. Since Fragment's getContext() method returns context of the parent Activity.



          mListener = (ConfirmDialogListener) context;


          This line sets your listener to be the parent Activity of the calling Fragment. Instead of setting mListener to the parent activity, you have to set it to the calling fragment.



          First, you have to set the target fragment for your DialogFragment while instantiating.



          DialogFragment confirmDialog = new ConfirmDialogFragment();
          confirmDialog.setTargetFragment(this, "CONFIRM_DIALOG_TAG");
          if (getFragmentManager() != null)
          confirmDialog.show(getFragmentManager(), "ConfirmDialogFragment");



          Now, inside your dialog fragment's onCreate, you can set the callback to be your fragment.



          try 
          mListener = (ConfirmDialogListener) getTargetFragment();
          catch (ClassCastException e)
          throw new ClassCastException(context.toString()
          + " must implement ConfirmDialogListener");



          And remove the code from onAttach method.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 28 at 5:10

























          answered Mar 27 at 4:52









          RanjanRanjan

          7618 silver badges16 bronze badges




          7618 silver badges16 bronze badges















          • Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

            – Jeff
            Mar 27 at 22:46











          • Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

            – Jeff
            Mar 27 at 23:54












          • I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

            – Ranjan
            Mar 28 at 5:09











          • Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

            – Jeff
            Mar 28 at 23:47






          • 1





            It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

            – Jeff
            Mar 29 at 13:32

















          • Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

            – Jeff
            Mar 27 at 22:46











          • Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

            – Jeff
            Mar 27 at 23:54












          • I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

            – Ranjan
            Mar 28 at 5:09











          • Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

            – Jeff
            Mar 28 at 23:47






          • 1





            It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

            – Jeff
            Mar 29 at 13:32
















          Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

          – Jeff
          Mar 27 at 22:46





          Tanjan, thank you for the information, especially the method that points to the calling Fragment. I'm having some difficulty at the moment because Android Studio is complaining about "this" as my ConfirmDialogFragment instantiation is performed in an anonymous method in ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(null, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) .... I have to figure out how to get this Fragment's reference using FragmentManager instantiated outside this anonymous method and pass it inside.

          – Jeff
          Mar 27 at 22:46













          Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

          – Jeff
          Mar 27 at 23:54






          Update: I seem to have successfully gotten the Fragment with thisFragment = fm.findFragmentById(R.id.fragment_container); Log.d(TAG, "thisFragment is: " + thisFragment); In LogCat I see MedicalInformationFragment: thisFragment is: MedicalInformationFragment7a40c18 #0 id=0x7f080088.

          – Jeff
          Mar 27 at 23:54














          I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

          – Ranjan
          Mar 28 at 5:09





          I think you can get the context directly by replacing this with ConfirmDialogFragment.this.

          – Ranjan
          Mar 28 at 5:09













          Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

          – Jeff
          Mar 28 at 23:47





          Thank you for your time! It now works for the calling Fragment, but not for the Activities that rely on it. So, my next effort is to either get it to work for both Activities and Fragments or simply create two AlertDialogs, one dedicated to Activities and one to Fragments. I'm learning on my own, so this takes me a while.

          – Jeff
          Mar 28 at 23:47




          1




          1





          It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

          – Jeff
          Mar 29 at 13:32





          It now works for both Activities and Fragments. I checked for getTargetFragment() == null, in which case the caller is an Activity, otherwise a Fragment. So, the if/else block handles it.

          – Jeff
          Mar 29 at 13:32








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55368094%2fcan-alertdialog-be-made-to-work-when-called-from-a-fragment%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript