【问题标题】:setText of TextView on Async Task complete异步任务上 TextView 的 setText 完成
【发布时间】:2015-02-06 13:26:37
【问题描述】:

我想在我的 android 应用程序中使用 ksoap2 网络服务返回一个特定的字符串。

Web 服务正在返回正确的值,但任务完成后设置的文本没有得到更新。我需要做一些事情(比如尝试打开导航抽屉)然后它会得到更新。有什么想法吗??

我的代码如下

// Calling the async class

protected void onResume() {
            try {
                super.onResume();
                new RetrieveTimeWS().execute();
            }
            catch (Exception e)
            {
                Log.e("Current Time", e.getMessage());
            }
        }

下面是异步任务

class RetrieveTimeWS extends AsyncTask<Void, Void, String> {

        protected String doInBackground(Void... params) {
            String datetime = "";
            try {

                TextView TVcurrentTime = (TextView) findViewById(R.id.DateTimeNow);

                TVcurrentTime.setText("Loading...");
                datetime = getDateTimeClass.getDateTime();
                TVcurrentTime.setText(datetime);

            } catch (Exception e) {
                Log.e("Async Task - GetDateTime ", e.getMessage());
            }
            return datetime;
        }
    }

只有在我触摸屏幕上的任何组件之前,文本字段才会显示“正在加载...”。 Web服务返回文本后,如何将文本视图更改为所需的字符串。

提前致谢。

拉克斯。

【问题讨论】:

标签: android android-asynctask textview


【解决方案1】:

您不能通过 UI 线程与 UI 交互。 AsyncTask 具有从 UI 线程调用的 onPreExecute 和 PostExecute 方法,您可以在其中更改 UI。

class RetrieveTimeWS extends AsyncTask<Void, Void, String> {

    TextView TVcurrentTime = (TextView) findViewById(R.id.DateTimeNow);

    Exception e;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();        
        TVcurrentTime.setText("Loading...");
    }

    protected String doInBackground(Void... params) {
        String datetime = "";
        try {           
            datetime = getDateTimeClass.getDateTime();
        } catch (Exception e) {
            this.e = e;
            Log.e("Async Task - GetDateTime ", e.getMessage());
        }
        return datetime;
    }

    @Override
    protected void onPostExecute(final String s) {
        super.onPostExecute(s);

        if (e != null) {
            TVcurrentTime.setText(s);
        }
    }
}

【讨论】:

  • 在 AsyncTask 中找不到viewById
【解决方案2】:

您不能在后台线程中进行任何 UI 工作。在 onPostExecute() 方法中执行此操作。 此方法在主线程上运行。所以,你可以在这个方法中设置文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多