Android gettextbeforecursor on inactive inputconnection

getTextBeforeCursor on inactive InputConnection, and other issue #2261

Comments

rachidev84 commented Feb 18, 2020 •

Flutter version: 1.12.13 + hotfix 8
minSdkVersion 21
targetSdkVersion 28

I/SurfaceView(27097): Punch a hole(dispatchDraw), this = io.flutter.embedding.android.FlutterSurfaceView
I/SurfaceView(27097): updateWindow — UPDATE_WINDOW_MSG, this = Handler (android.view.SurfaceView$1)
I/Choreographer(27097): Skipped 2 frames! The application may be doing too much work on its main thread.
V/PhoneWindow(27097): DecorView setVisiblity: visibility = 0, Parent = ViewRoot, this = DecorView@c92ba06[MainActivity]
D/FlutterView(27097): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@e56388c
D/Surface (27097): Surface::connect(this=0x7558c8b400,api=1)
W/libEGL (27097): [ANDROID_RECORDABLE] format: 1
D/mali_winsys(27097): EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
I/Choreographer(27097): Skipped 1 frames! The application may be doing too much work on its main thread.
D/GraphicBuffer(27097): register, handle(0x7558de8200) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/ViewRootImpl(27097): swipeFromBottom mIgnoring true downY 1868 mScreenHeight 1920 mStatusBarHeight 54
D/ViewRootImpl(27097): swipeFromBottom mIgnoring true downY 1868 mScreenHeight 1920 mStatusBarHeight 54
D/ViewRootImpl(27097): swipeFromBottom mIgnoring === false downY 1868 mStatusBarHeight 54
D/GraphicBuffer(27097): register, handle(0x756a992d80) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
I/SurfaceView(27097): updateWindow — setFrame, this = io.flutter.embedding.android.FlutterSurfaceView
I/SurfaceView(27097): Punch a hole(dispatchDraw), this = io.flutter.embedding.android.FlutterSurfaceView
W/IInputConnectionWrapper(27097): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(27097): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(27097): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(27097): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(27097): getTextBeforeCursor on inactive InputConnection
D/GraphicBuffer(27097): register, handle(0x7558dd7300) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
W/IInputConnectionWrapper(27097): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(27097): finishComposingText on inactive InputConnection
D/FlutterView(27097): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@e56388c
D/Surface (27097): Surface::disconnect(this=0x7558c8b400,api=1)
D/GraphicBuffer(27097): unregister, handle(0x7558dd7300) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/GraphicBuffer(27097): unregister, handle(0x756a992d80) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/GraphicBuffer(27097): unregister, handle(0x7558de8200) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/Surface (27097): Surface::disconnect(this=0x7558c8b400,api=1)
V/PhoneWindow(27097): DecorView setVisiblity: visibility = 4, Parent = ViewRoot, this = DecorView@c92ba06[MainActivity]
I/SurfaceView(27097): updateWindow — onWindowVisibilityChanged, visibility = 8, this = io.flutter.embedding.android.FlutterSurfaceView
D/Surface (27097): Surface::disconnect(this=0x7558c8b400,api=-1)
D/Surface (27097): Surface::disconnect(this=0x758cc55c00,api=1)
D/GraphicBuffer(27097): unregister, handle(0x756a901140) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/GraphicBuffer(27097): unregister, handle(0x756444f380) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/GraphicBuffer(27097): unregister, handle(0x75644501c0) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
D/Surface (27097): Surface::disconnect(this=0x758cc55c00,api=1)
W/IInputConnectionWrapper(27097): reportFullscreenMode on inexistent InputConnection
W/IInputConnectionWrapper(27097): finishComposingText on inactive InputConnection

The text was updated successfully, but these errors were encountered:

DanTup commented Feb 18, 2020

This output is coming from Flutter, so I don’t think there’s anything wrong in the VS Code extension here.

Do you see the same thing if you run from a terminal window with flutter run ?

rachidev84 commented Feb 19, 2020

@DanTup same issue with Android Studio, as you said it is coming from Flutter, can you please report this is to flutter team

DanTup commented Feb 19, 2020

@rachidev84 Flutter issues should be raised at https://github.com/flutter/flutter/issues. It’s better for you to raise the issue since that way if the Flutter team need more info it’s easier for them to ask you (and you’d also get notifications of updates).

Читайте также:  Не удалось загрузить виджет android что это

In this case however, it seems like there may already be an open issue that covers this:

You may wish to Subscribe to that issue for updates. I’ll close this one since there’s nothing to do in the VS Code extension. Thanks!

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

«getTextBeforeCursor on inactive InputConnection» warning when clearing text field using TextEditingController. #11321

Comments

anarchyrucks commented Jul 20, 2017 •

Steps to Reproduce

When input to the text field is submitted, the warning is generated.
The problem seems to be is with controller.clear() .

W/IInputConnectionWrapper(12446): getTextBeforeCursor on inactive InputConnection

Flutter Doctor

The text was updated successfully, but these errors were encountered:

j-maas commented Dec 4, 2017

I encountered this warning in my app as well and investigated it. It does not seem to be an issue with controller.clear() , but instead is correlated with the keyboard being open.

I’ve modified the sample by @anarchyrucks to also include a button that «submits» the text (code below). If I use either the keyboard’s submit button, or the added UI button while the keyboard is opened to process the TextInput, then I get the mentioned error message twice:

If however I close the keyboard and then press the button, no warning appears.

In a related StackOverflow discussion on this problem in Android are some mentions of keyboard and focus issues which led me to the above discovery. Unfortunately, there does not seem to be an explanation of what is really going on.

Code I used to test this, modified from @anarchyrucks’s version:

j-maas commented Jan 6, 2018

I have come across a StackOverflow answer stating that inactive InputConntection s can occur when the connection wasn’t closed using connection.close() .

As stated by @anarchyrucks, the errors only show if controller.clear() is called. If it is left out, no messages appear, regardless of whether you’re using the button or the keyboard to submit.

ghost commented Jul 24, 2018

@Y0hy0h @anarchyrucks I am getting the same warnings. I am using TextInputType.dateTime as my KeyboardType. I am getting those warnings as soon as I set my controller.text to some value. My code is bit different, I am using bloc pattern so I ain’t calling any setState method. But fundamentally it is the same thing. I get those warnings when I set the data in my controller.text, this leads to the cursor getting placed before my Text in the TextField. This is getting annoying as if I want to edit the data I have to move to the end of the string again and again. I you have any solutions for this, do notify me. Thanks!

raffomania commented Aug 11, 2018

I get this when using a TextFormField with autofocus: true and then setting .text to a value on my controller. When disabling autofocus: true , the warnings disappear.

tkshnwesper commented Aug 13, 2018 •

I get this even with autofocus: false . But with that, the warning appears after I move between different TextFormField s in my form 3 or 4 times whereas with autofocus enabled, it appears when I click on a TextFormField once.

Читайте также:  Блокировка вызовов для андроид как отключить

Update:
I happen to be using different keyboards for different fields, and I noticed that when the autofocus is off, the warning only appears when switching from a keyboard of type TextInputType.text to TextInputType.number .

As @Y0hy0h mentioned, it probably has something to do with the keyboard.

tkshnwesper commented Aug 14, 2018

Oh my goodness, folks! I managed to resolve the issue while trying to fix something else.

Read the contents of this link carefully. It fixed everything for me. 🎉

ghost commented Aug 14, 2018

@tkshnwesper Please be more precise.

tkshnwesper commented Aug 14, 2018

I never actually had to clear the text in the text field like in the example above within my application. In my application I had multiple text fields with different keyboard types and toggling between them caused the warning to come up. I was able to resolve that issue with the help of the link I posted above.

I was just looking into how to resolve @Y0hy0h ‘s example using something similar. But it seems like there might be a bug because no matter what I try, the warning pops up.

tkshnwesper commented Aug 15, 2018

So I decided to take one last shot at this. I added the text field clearing logic to my code and guess what! I got no warning! 🎉

Here’s my code, knock yourselves out 🍺

AoraMD commented Mar 6, 2019

Same problem here. I found that the problem has arisen only textfield is in a StatelessWidget. it never happens when in a stateful one.

Источник

GetExtractedText на неактивное предупреждение InputConnection на Android

В моем logcat появляется следующее предупреждение.

Я не могу найти причину этого. Пожалуйста, помогите

ОТВЕТЫ

Ответ 1

У меня возникла аналогичная проблема. Мой логарифм:

Моя ситуация: У меня есть EditText, в который входят типы пользователей. EditText очищается, когда пользователь нажимает кнопку. Когда я быстро нажимаю кнопку, происходит много неактивных записей InputConnection.

Последняя строка в моем logcat выше дает отличное представление о том, что происходит. Разумеется, InputConnection перегружен запросами на очистку текста. Я попытался изменить код, чтобы проверить длину текста, прежде чем пытаться его очистить:

Это помогает смягчить проблему в том, что нажатие кнопки быстро не вызывает поток предупреждений IInputConnectionWrapper. Однако это все еще подвержено проблемам, когда пользователь быстро чередуется между вводом чего-то и нажатием кнопки или нажатием кнопки, когда приложение находится под достаточной нагрузкой и т.д.

К счастью, я нашел другой способ очистить текст: Editable.clear(). С этим я вообще не получаю предупреждений:

Обратите внимание, что если вы хотите очистить все входное состояние, а не только текст (autotext, autocap, multitap, undo), вы можете использовать TextKeyListener.clear( Редактируемый e).

Ответ 2

Обновление:

Причина, по которой я получал предупреждения InputConnection, была не из-за того, где я устанавливал текст (т.е. в обратном вызове onTextChanged или afterTextChanged )), потому что я использовал setText .

У меня возникла проблема, позвонив:

Примечание. Я все равно делаю вызов в обратном вызове afterTextChanged , хотя он работает и без предупреждений от onTextChanged .

Предыдущий ответ:

Я тоже получал одинаковые сообщения в logcat, хотя мой сценарий несколько отличался. Я хотел прочитать каждый символ, который попал в EditText (или скомпонованные символы/вставленный текст), а затем reset рассматриваемый EditText в строку инициализации по умолчанию.

Четкая текстовая часть работает в соответствии с решением Джонсона выше. Однако сброс текста был проблематичным, и я получил предупреждения о подключении.

Читайте также:  Sasgis org для андроид

Первоначально my onTextChanged(CharSequence s, . ) определялся следующим образом:

Когда вызывается onTextChanged(. ) , EditText находится в режиме readonly. Я не уверен, что это означает, что мы не можем сделать больше, чем называть getText.clear() на нем ( setText(. ) вызовы также вызывают предупреждения ввода).

Однако обратный вызов afterTextChanged(Editable s) является правильным местом для установки текста.

Это пока работает без каких-либо предупреждений.

Ответ 3

Из справочных документов

Интерфейс InputConnection является каналом связи с InputMethod возвращается к приложению, которое получает его вход. это используется для выполнения таких вещей, как чтение текста вокруг курсора, ввод текста в текстовое поле и отправка сырых ключевых событий в приложение.

Кроме того, дальнейшее чтение показывает

getExtractedText(): Этот метод может выйти из строя, если входное соединение недействительно (например, сбой процесса), или клиент слишком долго ответьте текстом (ему нужно вернуть пару секунд). В в любом случае возвращается null.

Он также отслеживает изменения в этом тексте и предупреждает изменения.

Чтобы найти проблему, вам нужно будет исследовать любые запросы к базе данных, которые вы делаете, возможно, вокруг listViews или списков в макете.

Если у вас нет каких-либо представлений, например, случайное событие происходит в фоновом режиме, я бы предположил, что это не элемент элемента интерфейса, поэтому игнорируйте текстовые поля и т.д. Это может быть справочная служба, которая хранит информацию в курсоре или запрашивает курсор.

Кроме того, проблема возникает из вашего приложения? или, возможно, кто-то еще, который вы недавно установили. Перечислите полную трассировку logCat. Кто-то может признать проблему.

Я бы поставил под сомнение, что если вы не написали что-то конкретное, то это сообщение о некотором elses log log или, возможно, библиотеке, которую вы используете?

Ответ 4

У меня была такая же проблема. Предупреждение появилось, когда мягкая клавиатура была активирована в одном из моих EditTexts и активность потеряла фокус.

Я сделал, чтобы скрыть клавиатуру в onPause();

Ответ 5

Решил эту проблему для себя, может быть, у вас такая же проблема.

Это вызвано Объектом в HeaderView Адаптер списка.

Я надул Вид и объявил Object и разместил на нем TextWatcher.

Добавил его в Адаптер списка и построил адаптер.

Все прекрасно работает Text Watcher.

НО, если я когда-либо перестраивал адаптер после начальной сборки.

Этот HeaderView также перестроен.

Это предупреждение будет отображаться, потому что объект Объект удален, и текстовый наблюдатель все еще установлен для просмотра.

Адаптер Список и Объект были заменены, и я предполагаю, что Text Watcher смотрел в другую сторону, когда это произошло.

Итак, предупреждение отключается, и чудесным образом Text Watcher находит HeaderView и Объект. Но он теряет фокус и регистрирует это предупреждение.

НО, если у Объекта внутри Адаптер, а Текстовый наблюдатель прикреплен к Объект внутри адаптера . Тогда вам может потребоваться немного больше работы.

Попробуйте удалить прослушиватель и присоединить его снова после выполнения любой работы, которую вы можете выполнять.

Ответ 6

Помимо ответа antoniom, убедитесь, что любые дальнейшие действия, которые необходимо выполнить, действительно выполняются после скрытия клавиатуры, поэтому, если вы скрыли клавиатуру, подобную приведенной ниже:

вам нужно выполнить последующие действия после скрытия клавиатуры, например:

Ответ 7

У меня была эта проблема, когда мне пришлось модифицировать или получать текст из EditText, и это было сфокусировано.

Итак, прежде чем модифицировать или получить от него, я закрыл клавиатуру и исправил ее.

Возможно, ваша проблема другая.

Ответ 8

Я решил проблему с вводом типа ввода в xml следующим образом: андроид: inputType = «нет | текст | textCapWords | textUri»

до этого был android: inputType = «text» Это решило мою проблему.

Источник

Оцените статью