2012-01-28 46 views
0

數據發送回與UI我有這樣的AsyncTask,我用它來在互聯網上發送聊天信息。問題是,當我執行任務時,什麼事都沒有發生 - 至少不是在UI上。我懷疑onProgressUpdate()根本不執行。這個想法是,當任務開始時,一條消息將通過互聯網發送,用戶界面上的EditText將用新文本更新。這是全班同學:無法從的AsyncTask

import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.InetAddress; 
import java.net.MulticastSocket; 

import android.os.AsyncTask; 
import android.widget.EditText; 

public class Messager extends AsyncTask<SocketAndEditText, Void, Void> { 

    private MulticastSocket socket; 
    private EditText host; 
    private EditText port; 
    private EditText sendMessage; 
    private EditText messageBoard; 
    private InetAddress serverAddress; 
    private int pt; 
    private String newConverstion; 
    private String message; 

    @Override 
    protected Void doInBackground(SocketAndEditText... soEd) { 
     // get the text that they contain and add the new messages to the old ones 
     //host = soEd[0].getHost(); 
     //port = soEd[0].getPort(); 
     messageBoard = soEd[0].getMessageBoard(); 
     sendMessage = soEd[0].getSendMessage(); 

     message = sendMessage.getText().toString(); 
     String conversation = messageBoard.getText().toString(); 

     newConverstion = conversation.concat("\n[You] ").concat(message); 

     return null; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     // make the messages text view editable 
     messageBoard.setFocusable(true); 
     messageBoard.setText(newConverstion); // add the new message to the text view 
     messageBoard.setFocusable(false); // make the messages text view not editable 

     // erase the text on the second text view that has just been sent 
     sendMessage.setText(""); 

     sendMessage(message); 
    } 

    public void sendMessage(String message) { 
     // convert the host name to InetAddress 
     try { 
      serverAddress = InetAddress.getByName("localhost"); 
     } catch (Exception e) {} 
      pt = 4456; 

     // create socket and start communicating 
     try { 
      socket = new MulticastSocket(pt); 
      socket.joinGroup(serverAddress); 
     } catch (IOException e) {} 

     // Send message to server 

     // convert message to bytes array 
     byte[] data = (message).getBytes(); 

     // create and send a datagram 
     DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, pt); 

     try { 
      socket.send(packet); 
     } catch (IOException e) {} 
    } 

} 

出了什麼問題?

回答

1

onProgressUpdate應該從doInBackground中顯式調用,如所見here。這不是在你的情況下使用的正確方法。我寧願期望文本字段的設置應該在onPostExecute中完成。原因是newConverstion的值是在遠程調用後確定的,可能需要一段時間才能完成。如果你在asynctask完成執行之前做了這個,你就冒NPE的危險。

編輯添加一些代碼:

public class Messager extends AsyncTask<SocketAndEditText, Void, Void> { 

    //skipping some field declaration 

    @Override 
    protected Void doInBackground(SocketAndEditText... soEd) { 
     // get the text that they contain and add the new messages to the old ones 
     //host = soEd[0].getHost(); 
     //port = soEd[0].getPort(); 
     messageBoard = soEd[0].getMessageBoard(); 
     sendMessage = soEd[0].getSendMessage(); 

     message = sendMessage.getText().toString(); 
     sendMessage(message); //NOTE: added the remote call in the background method. This is the only thing that really SHOULD be done in background. 

     String conversation = messageBoard.getText().toString(); 

     newConverstion = conversation.concat("\n[You] ").concat(message); 

     return null; 
    } 

    protected void onPostExecute(Void result) { 
     // make the messages text view editable 
     messageBoard.setFocusable(true); 
     messageBoard.setText(newConverstion); // add the new message to the text view 
     messageBoard.setFocusable(false); // make the messages text view not editable 

     // erase the text on the second text view that has just been sent 
     sendMessage.setText(""); 
    } 

基本上最重要的事情是把最耗時的任務的背景下調用。在你的情況下,這是sendMessage。從此,您可以在postExecute和preExecute中執行所需的任何修復。我不太確定你的onProgressUpdate意圖是什麼。我剛剛把它翻譯成使用onPostExecute。如果您需要暫時禁用該字段,可以在onPreExecute中將其禁用,並將其onPostExecute啓用。如果你不叫publishProgress()自己

+0

Здрасти,имашлипредставакоеточновкоиметодидасложа? ТезиAsyncTasksнапълномеобъркахасвсичкитеимметодиипараметри。 МеждудруготоможешлидапрепоръчашнякаквочетивозамрежовопрограмираненаАндроид,чеазненамирампочтинищосериозно。 Мерсиипоздрави。 – RegedUser00x 2012-01-29 12:56:21

+0

@ RegedUser00x:我被抓到了,我真的是保加利亞人。我也很喜歡我的語言,並且更喜歡說它。但是,這是社區網站,您應該同意我們的語言,雖然特殊,但不適用於SO的官方語言。翻譯你的文章: '嗨,你知道在哪種方法中放置什麼? AsyncTask類將我的所有方法都弄糊塗了。順便說一下,你可以指點我一些書來了解Android中的網絡編程,因爲我幾乎找不到任何東西。 Thanks.' – 2012-01-29 13:34:35

1

onProgressUpdate()不會被調用。請參閱the 4 steps of AsyncTask

正如鮑里斯指出。您應該撥打sendMessage(),doInBackground()並更新onPostExecute()中的用戶界面。

+0

我已經照你們也勸我,但現在我得到'socket.send(包)一個NullPointerException異常;'猜東西是錯誤的聯網? – RegedUser00x 2012-01-29 13:48:10

+1

刪除Socket初始化的try catch。我想這隱藏了真正的問題 - IOExcaption – 2012-01-29 13:57:31