Search code examples
androidandroid-spinnerandroid-popupwindow

Bad token exception on spinner which uses (android:entries="@array/type") in fragment


When I run my code on some devices (Like MI note 4) it gives me an exception:

android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W@7989790 is not valid; is your activity running?

But when I run this on a high speed and latest mobile (MI note 5 pro) it works fine. I can't understand the error here, please guide me thanks.

Here is XML for the spinner :-

<Spinner
    android:id="@+id/type_spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/dp_10"
    android:entries="@array/type" />

and my string array:

<string-array name="type">
     <item>Every Month</item>
     <item>Every Year</item>
     <item>Once</item>
</string-array>

add_reminder.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.add_reminder, null);

        final PopupWindow pw = new PopupWindow(view1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        pw.setFocusable(true);
        pw.setTouchable(true);
        pw.showAtLocation(view, Gravity.CENTER, 0, 0);


        final Spinner type = view1.findViewById(R.id.type_spinner);
});

My fragment is still running in behind a pop-up, so this error must not be appearing since it shows that activity is not running. And remember it's running OK on latest device.


Solution

  • I solved that error by putting my popup's XML code in fragment and make it visible on click. By that way spinner's code runs nicely on every device that way error must be somewhere in using spinner in custom popup.