2015-02-06 143 views
-2

我想在我的android應用程序中使用kso​​ap2 web服務返回特定的字符串。TextView上的setText異步任務完成

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服務返回文本後將textview更改爲所需的字符串。

在此先感謝。

Laks。

+2

在onPostExecute(); http://stackoverflow.com/questions/8369539/android-on-post-execute-in-asynctask – 2015-02-06 13:29:33

回答

4

您不能從UI線程與UI進行交互。 AsyncTask擁有從UI線程調用的onExExcute和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); 
     } 
    } 
} 
+0

你不能findviewById在AsyncTask – hyperfkcb 2017-05-19 02:12:31

0

你不能在後臺線程中做任何UI工作。在onPostExecute()方法中執行。 此方法在主線程上運行。所以,你可以在這個方法中設置文本。