首页 > 解决方案 > 如何从 FragmentActivity 显示 CustomDialog

问题描述

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

我得到的错误:

android.view.WindowManager$BadTokenException: 无法添加窗口 -- 令牌 null 不适用于应用程序

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

注意:我删除了一些与我的问题无关的代码

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(); 
                
            }
        }
        
    });

}

这是我显示CustomDialog的方法:

UserInfoShower 方法

注意:我删除了一些与我的问题无关的代码

    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();
                            }
                        });

                    }
                });







}

当我调用 cdd.show(); 时发生错误

这是 UserInfoShower 对话框:

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;
}

}

这是我的对话框 xml 文件:

<?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>

最后是整个错误日志:

在此处输入图像描述

希望你能帮助我。干杯!

标签: androidcustomdialog

解决方案


问题解决:@dr3k

这是解决方案。解决方案


推荐阅读