5

I am trying to do a long click in an EditText, but when I do a long Click, I receive the error below. I would like to be able to do a long click to get the Copy/Paste/Select All context popup so that the user can paste text into the box.

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

The EditText is in a ScrollView in a PopupWindow. So when the error occurs, I am currently active on an Activity with the PopupWindow open and I do a Long Click within the EditText that is contained on the PopupWindow.

Gradle Settings

compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
    applicationId 'com.accoservice.cico'
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 37
    versionName '4.2.6'
    multiDexEnabled true
}

Layout Containing the EditText:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/outer_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#73000000">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="5dp"
        android:background="#ffffff"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="15dp"
            android:singleLine="true"
            android:text="@string/note_msg"
            android:textColor="#62CCFE"
            android:textSize="18sp" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="10dp"
            android:background="#62CCFE" />

        <ScrollView
            android:id="@+id/sv_resolution_note"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">

            <EditText
                android:id="@+id/et_note_msz"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/view"
                android:layout_alignParentTop="true"
                android:scrollbars="vertical"
                android:focusable="true"
                android:gravity="left"
                android:maxLines="20"
                android:hint="@string/write_note"
                android:inputType="textFilter|textMultiLine|textCapSentences"
                android:singleLine="false"
                android:textIsSelectable="true"
                android:enabled="true"
                android:longClickable="true" />
        </ScrollView>

        <View
            android:id="@+id/view"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_above="@+id/send_note"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:background="@android:color/darker_gray" />

        <Button
            android:id="@+id/send_note"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/viewss"
            android:layout_gravity="center"
            android:background="@color/white"
            android:text="@string/add_note" />

        <View
            android:id="@+id/viewss"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"

            android:background="@android:color/darker_gray" />

    </LinearLayout>

</LinearLayout>

Pop up the Window:

@Override
public void onClick(View v) {
     noteDialog(getResources().getString(R.string.laborentryresolutionstart), tv_labor_entry_resolution_start);
}

public void noteDialog(String noteTitle, final TextView tv_resolution_note)
{
    LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
            final View popupView;
            popupView = layoutInflater.inflate(R.layout.resolution_note, null);

            TextView title = (TextView) popupView.findViewById(R.id.title);
            title.setText(noteTitle);

            final EditText editText = (EditText) popupView.findViewById(R.id.et_note_msz);
            final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.update();
            popupWindow.setFocusable(true);
            popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            editText.setEnabled(false);
            editText.setEnabled(true);
            editText.setFocusable(true);
            editText.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    //ADD HERE ABOUT CUT COPY PASTE
                    // TODO Auto-generated method stub
                    return false;
                }
            });

            if (!tv_resolution_note.getText().toString().isEmpty()) {
                editText.setText(tv_resolution_note.getText().toString());
            }

            Button btnDone = (Button) popupView.findViewById(R.id.send_note);
            LinearLayout outer_layout = (LinearLayout) popupView.findViewById(R.id.outer_layout);
            outer_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow.dismiss();

                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);
                }
            });

            System.gc();
            try {
                btnDone.setOnClickListener(new Button.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EditText noteMsz = (EditText) popupView.findViewById(R.id.et_note_msz);
                        tv_resolution_note.setText(noteMsz.getText().toString());

                        popupWindow.dismiss();

                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);

                        invalidateOptionsMenu();
                    }
                });
            } catch (Exception e) {
            }

            popupWindow.setFocusable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable(null, ""));
            popupWindow.showAsDropDown(tv_labor_sym_entry, 0, -60);
            popupWindow.update();     
}
Adam
  • 497
  • 2
  • 9
  • 29
  • Are you calling this code in an Activity? A service? Are you sure you haven't been taken off screen if an Activity? That message usually occurs when you try to launch a UI from a Service, or when you try to pop up a dialog after the activity is done. – Gabe Sechan Sep 08 '17 at 17:45
  • I am calling the code for the popup window while on an Activity. The activity is currently running, the popup window is active and I do a long press in the EditText and receive the error. – Adam Sep 08 '17 at 18:45
  • 1
    I ran your code with slight modification on an emulator running API 24 and it works OK for me. That is to say it is not crashing and the long press listener is invoked as expected. Can you supply some more information about how you are setting things up? API you're testing on? [Here](https://gist.github.com/Cheticamp/08ebef491a727a12577a7e9790eaa752) is a gist of the activity I used in case it helps you. – Cheticamp Sep 11 '17 at 17:37
  • gradle settings: compileSdkVersion 25, minSdkVersion 17, targetSdkVersion 25 – Adam Sep 11 '17 at 18:04
  • It looks like you are doing exactly what I am doing. My EditText is inside a ScrollView if that makes a difference. – Adam Sep 11 '17 at 18:09
  • @Adam I used your layout, so my `EditText` is also in a `ScrollView`. I had to add some code to actually show the popup. That is not in your sample code. What you have presented works, so something else is going on. Where are you executing your code from? Can you share that? btw, commenters on posts aren't notified of comments unless they authored the posting. (I didn't see your comments above until I explicitly checked.) Just tag the commenter with @username, e.g., @Cheticamp. – Cheticamp Sep 12 '17 at 01:48
  • I have tested and found that `onLongClick` on EditText in PopupWindow work well with no error. Maybe your problem came from another reason. Do you have any specific thing in your project – Linh Sep 12 '17 at 02:18
  • @Cheticamp I added the onclick method that calls the method for creating the popup so that you could see that. I also added all the code that is in the notedialog so that you could see the full method. Thanks! – Adam Sep 12 '17 at 13:29
  • Can you please share the crash logs? – Surendra Kumar Sep 18 '17 at 09:10

4 Answers4

4

According to me, the reason that you're getting this error is that the outer_layout's onClickListener gets fired along with the onLongClickListener of your editText. And, since popupWindow.dismiss is called inside the click listener of your outer_layout, the popup window gets dismissed before your editText's long click listener code can run, thus causing the error.

The simplest solution to this would be to return true for your onLongClick method :-

editText.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    //ADD HERE ABOUT CUT COPY PASTE
                    // TODO Auto-generated method stub
                    return true;
                }
            });

By doing so, you will consume the given long click, and it won't fire up any other unwanted listeners.

onLongClick() - This returns a boolean to indicate whether you have consumed the event and it should not be carried further. That is, return true to indicate that you have handled the event and it should stop here; return false if you have not handled it and/or the event should continue to any other on-click listeners.

Rohan Stark
  • 2,346
  • 9
  • 16
0

You may be calling your popup too early. In my example (gist here), I am executing the popup code from a button press. This is after onCreate() and the other key lifecycle methods run. With the example, everything works OK.

If, however, I try to instantiate the popup in onCreate(), I get a logcat error that states: "android.view.WindowManager$BadTokenException: Unable to add window" which is what you are seeing.

I believe that you are trying to instantiate your popup too soon. Start it later in the activity's life cycle and definitely after onCreate() executes. If you need to instantiate it pronto, you could attach the code to the UI message queue via a call to post(Runnable). (See here).

I am fairly certain that this is your issue. If this doesn't help, update your question with more information about how and when you instantiate the popup window.

Cheticamp
  • 61,413
  • 10
  • 78
  • 131
  • I added more code to the question so that you can see more of what is going on. – Adam Sep 12 '17 at 13:31
  • @Adam I can't reproduce your issue with what you have supplied. If you continue to be stuck on this, I suggest that you create a [MCVE](https://stackoverflow.com/help/mcve) that reproduces the problem. – Cheticamp Sep 12 '17 at 15:25
0

in your main Activity

private Content mContext;

public void onCreate(){
 mContext = this;
}

replace getBaseContext() with mContext

LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

or

  LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
Karthick
  • 281
  • 2
  • 7
0

We went with a redesign to take away the popup and eliminate the bug that was there.

Adam
  • 497
  • 2
  • 9
  • 29