2016-02-20 79 views
1

我有一個AsyncTask,它充當客戶端並從服務器獲取字符串並將其放入String。任務完成後,我使用服務器的響應,但數據尚未更改 - 它爲空。Android如何等待AsyncTask完成

connectBtn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     ... 
     Client myClient = new Client(responseTV); 
     myClient.execute(); 

     if (responseStr.charAt(0) == '1') { <----- responseStr is null 
      changeBrightness(Integer.parseInt(responseStr.substring(1))); 
     } 
    } 
}); 

我假設的代碼保持.execute()後去這不是我的情況非常好。

更新:爲客戶端類添加代碼。

public class Client extends AsyncTask<Void, Void, Void> { 

    String response = ""; 
    TextView responseTV; 

    public Client(TextView responseTV) { 
     this.responseTV = responseTV; 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     Socket socket = null; 

     try { 
      socket = new Socket(IP, PORT); 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(BUFFER_SIZE); 
      byte[] buffer = new byte[BUFFER_SIZE]; 

      int bytesRead; 
      InputStream inputStream = socket.getInputStream(); 

      while ((bytesRead = inputStream.read(buffer)) != -1) { 
       byteArrayOutputStream.write(buffer, 0, bytesRead); 
       response += byteArrayOutputStream.toString("UTF-8"); 
      } 
     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
      response = "UnknownHostException: " + e.toString(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      response = "IOException: " + e.toString(); 
     } finally { 
      if (socket != null) { 
       try { 
        socket.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     //Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show(); 
     responseTV.setText(response); 
     responseStr = response; 
     super.onPostExecute(aVoid); 
    } 
} 
+0

你可以發佈'客戶端'類的代碼嗎? – Mussa

+0

對,使用回調/(功能)接口:) – Leandro

+2

您不必等待調用'AsyncTask'的結果。您可以在'AsyncTask'的onPostExecute方法中獲得結果並更新您的視圖。你也可以發佈你的'AsyncTask'類 – Sharj

回答

3
if (responseStr.charAt(0) == '1') { <----- responseStr is null 
      changeBrightness(Integer.parseInt(responseStr.substring(1))); 
     } 

使用此代碼的AsyncTaskonPostExecute()方法。它在UI thread上運行,並且在完成doInBackground()的工作後正是您需要的方法。