如何从 FragmentActivity 显示 CustomDialog

How to show CustomDialog from FragmentActivity

我在显示来自 FragmentActivity 的自定义对话框时收到下面写的错误。

Error i am getting :

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

这是我的 DriverMapActivity,我从中显示自定义对话框:

Note: I removed some codes that they are not related to my question

DriverMap FragmentActivity

public class DriverMapActivity extends FragmentActivity{

private GoogleMap mMap;
GoogleApiClient googleApiClient;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
private Location lastLocation;
private FirebaseAuth mAuth;
private Switch workingswitch;
private String customerId, userId;
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private DatabaseReference driverInfoDB;
private String name, surname, profileimageURL;
private String distancetopick,distancetodes;
private int distancefinal;
private Button yesBtn, noBtn;
private UserInfoShower cdd;
private int cameraupdatedandzoomed;
private Map<String,String> infoMap;
private LatLng pickupLoc;
private LatLng destiantionLoc;
private Marker pickupMarker, destinationMarker;
private float rideDistance;
private Button btnzoom;
private String customerprofileUrl;


private Button logoutbtn, settingsbtn, historybtn, opendrawer;
private boolean pickupgeted;
private String rideStatus = "";
private LatLng target;

@SuppressLint("NewApi")
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_driver_map);
   
    customerId = "";
    cameraupdatedandzoomed=0;
    mAuth = FirebaseAuth.getInstance();
    toolbar = findViewById(R.id.toolbar);
    polylines = new ArrayList<>();
    userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
    btnzoom=findViewById(R.id.btnzoom);
    pickupgeted = false;

    startService(new Intent(DriverMapActivity.this,onAppKilled.class));
    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(this);

    // This method will trigger on item Click of navigation menu


    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);

    setDriverStuffToNavView();

    btnzoom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(lastLocation!=null)
            {

            }
            else
            {
                Toast.makeText(DriverMapActivity.this, "Turn on Working 
            }

        }
    });
private void listenForCustomerRequest() {
    String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); 
DatabaseReferencelistenerRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Drivers").child(userId).child("CustomerRequest");
    listenerRef.addChildEventListener(new ChildEventListener() {
 public void onChildAdded(@NonNull DataSnapshot dataSnapshot, String s) {
          
            if (dataSnapshot.exists()) {       
                customerId = dataSnapshot.getKey(); 
                showUserInfo(); 
                
            }
        }
        
    });

}

Here is method that i show CustomDialog:

UserInfoShower 方法

Note: I removed some codes that they are not related to my question

    private void showUserInfo() {
DatabaseReferenceuserinfoRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
    Log.i("TEST", "CustomerId Comes Driver " + customerId);
    infoMap=new HashMap<>();
    cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
DatabaseReferenceuserInfoDB=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
    userInfoDB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
 if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
                Map<String, Object> map = (Map<String, Object>)
dataSnapshot.getValue();
                infoMap.put("DriverOrCus", "1");
                infoMap.put("Name", map.get("name").toString());
                infoMap.put("Surname", map.get("surname").toString());
                if(map.get("profileimageURL") !=null)
                {
                    infoMap.put("profileimageURL",
map.get("profileimageURL").toString());
                 customerprofileUrl=map.get("profileimageURL").toString();
                }

                infoMap.put("customerId", customerId);
                cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
                cdd.show();
                cdd.setCanceledOnTouchOutside(false);
                yesBtn = cdd.findViewById(R.id.yesBtn);
                noBtn = cdd.findViewById(R.id.noBtn);




                yesBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String userId=FirebaseAuth.getInstance().
  getCurrentUser().getUid();
                        
 DatabaseReference decisionRef=FirebaseDatabase.
 getInstance().getReference().
child("Users").child("Drivers").child(userId).child("CustomerRequest")
.child(customerId)
                                .child("driverDecision");

decisionRef.setValue("YES").addOnCompleteListener(newOnCompleteListener
<Void>() {
                            @Override
                            public void onComplete(@NonNull
Task<Void>task) {
                                cdd.cancel();
                                cdd.dismiss();
                                cdd=null;
                                getCustomerRideInfo();
                            }
                        });

                    }
                });







}

Error happens when i call cdd.show();

Here is UserInfoShower Dialog:

public class UserInfoShower extends Dialog {
public Context c;
private Button noBtn, yesBtn;
private String name, surname, profileimageURL;
private TextView customerName, customerSurname;
private ImageView customerprofile;
private int position;
private String driverId;
private LatLng CustomerPickupLoc, CustomerDestinationLoc;
private String customerId, desName;
private  SharedPreferences sharedpref;
Map<String,String> infoMap;

public UserInfoShower(Context a,Map<String,String> infoMap) {
    super(a);

    this.c = a;
    this.infoMap=infoMap;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_customer_info_shower);
    noBtn = findViewById(R.id.noBtn);
    yesBtn = findViewById(R.id.yesBtn);
    customerName = findViewById(R.id.customerName);
    customerSurname = findViewById(R.id.customerSurname);
    customerprofile = findViewById(R.id.customerprofile);


    position = Integer.valueOf(infoMap.get("DriverOrCus"));

    if (position == 1) {
        showCusInfo();
    } else {
        showDriverInfo();
    }

    yesBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (position == 1)             // If user is Driver
            {

                        dismiss();

            } else   //if user is Cusomer And Liked Driver
            {
                dismiss();
            }
        }
    });
    noBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (position == 1) //if User is Driver
            {

                dismiss();


            } else// if User is Customer And not liked Driver
            {
                dismiss();
            }


        }
    });


}




private void showCusInfo() {
    name = infoMap.get("Name");
    surname = infoMap.get("Surname");
    customerId = infoMap.get("customerId");
   
    customerName.setText("Name " + name);
    customerSurname.setText("Surname " + surname);

}

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();

}

public static boolean isValidContextForGlide(final Context context) {
    if (context == null) {
        return false;
    }
    if (context instanceof Activity) {
        final Activity activity = (Activity) context;
        if (activity.isDestroyed() || activity.isFinishing()) {
            return false;
        }
    }
    return true;
}

}

Here is My Dialog xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://
schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UserInfoShower">

<ImageView
    android:id="@+id/customerprofile"
    android:layout_width="90dp"
    android:layout_height="102dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="30dp"
    android:layout_marginTop="35dp"
    android:src="@drawable/customer"
    tools:ignore="RtlCompat" />



<TextView
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:id="@+id/customerName"
    android:layout_alignParentTop="true"
    android:layout_marginTop="36dp"
    android:layout_toEndOf="@+id/customerprofile"
    android:text="Name : Vuqar"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="20sp"
    tools:ignore="RtlCompat" />

<TextView
    android:id="@+id/customerSurname"
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="92dp"
    android:layout_toEndOf="@+id/customerprofile"
    android:text="Surname : Samed"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="20sp"
    tools:ignore="RtlCompat" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="219dp"
    android:orientation="horizontal">

    <Button
        android:id="@+id/yesBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="OK.Looks Good" />

    <Button
        android:id="@+id/noBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Nope" />
</LinearLayout>



</RelativeLayout>

And finally here is whole error log :

Hope you can help me.Cheers !

问题解决者:@dr3k

这是解决方案。 Solution