【问题标题】:Get Error - The method getText must be called from the UI thread, currently inferred thread is workerGet Error - 必须从 UI 线程调用 getText 方法,目前推断线程为 worker
【发布时间】:2017-02-23 07:36:43
【问题描述】:

在下面的行中,它给了我错误提示:

getText 方法必须在 UI 线程中调用,目前推断线程为 worker”。

我该如何解决这个错误?

// Get the text from EditText
String wordsToTranslate = **translateEditText.getText()**.toString();

粗体部分是它告诉我有错误的地方。关于如何解决这个问题的任何想法?

Screen shot of the error

【问题讨论】:

  • “doInBackgound”方法中不能做UI相关的操作
  • 您只能从 UI 线程使用 UI(EditText 是 UI 的一部分)。 doInBackground 应该在后台线程中调用。那就是问题所在。在doInBackground之外获取文本,例如在onPreExecute
  • 感谢你们的快速反应。我只需要删除那行代码并将其放在覆盖之前(意思是在 doInBackground 之外),它就解决了问题。感谢所有的帮助。 :)

标签: java android multithreading


【解决方案1】:

试试这个:

String wordsToTranslate = translateEditText.getText().toString();

new Translate().execute(wordsToTranslate);

class Translate extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... args) {
            // Building Parameters
            String wordsToTranslate = args[0];


            //do your work

    }

}

【讨论】:

    【解决方案2】:

    每个应用都有自己的运行 UI 对象的特殊线程,您只能从该线程访问 UI 对象。

    您应该查看有关与 UI 线程通信的 android 开发者网站:

    https://developer.android.com/training/multiple-threads/communicate-ui.html

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多