【问题标题】:Invalid return type fragment thread无效的返回类型片段线程
【发布时间】:2018-04-23 18:31:19
【问题描述】:

我在 Android IDK 中创建了一个线程,为什么它说返回类型无效! 我想要的只是显示我从Profile 得到的json 我想更改片段中的文本

Thread thread= new Thread(){
          if (getActivity()!=null)
          {
              getActivity().runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                      Profile profile = service.getProfile(text);
                      Gson gson = new Gson();
                      String json = gson.toJson(profile);
                      output.setText(json.toString());
                  }
              });
          }
      };
        thread.start();

【问题讨论】:

  • 它在哪里说“无效的返回类型”?另外,为什么你甚至需要这个线程?如果您想在后台线程上运行 getProfile,您可能需要查看 AsyncTask。
  • 我尝试了异步任务然后放弃了,if (getActivity()!=null) 这里说。如果你可以把它变成异步任务,我的@DennisK 没问题
  • 好的,我将使用 AsyncTask 发布一个可能的解决方案。但是您需要学习交易工具。在 android 中直接使用 Threads 并非易事,如果您尝试,可能会导致更多问题。

标签: android multithreading personality-insights


【解决方案1】:

试试这个

    new AsyncTask<Void, Void, Void> (){
        private String json;

        protected Void doInBackground(Void... voids) {
            Profile profile = service.getProfile(text);
            Gson gson = new Gson();
            json = gson.toJson(profile);
            return null;
        }

        protected void onPostExecute(Void result) {
            output.setText(json);
        }
    }.execute();

【讨论】:

  • 抱歉,省略了()。立即尝试
  • 它需要 doInBackground() 参数
  • 抱歉,我不在开发 PC 上。固定的。您也可以只使用 IDE 的自动建议来实现方法。
  • 该方法看起来不错,但抛出 java.net.UnknownHostException: Unable to resolve host "gateway.watsonplatform.net": No address associated with hostname
  • 嗯,那是您的服务无法连接。您没有提供此代码,如果您自己无法弄清楚,这可能是一个新问题。
猜你喜欢
  • 2012-02-07
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2019-05-07
  • 2022-12-06
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
相关资源
最近更新 更多