2012-01-28 58 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