且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

机器人的AsyncTask方法不显示数据

更新时间:2021-12-12 05:44:08

我的猜测是,这个问题的出现是因为你没有正确关闭客户端 PrintWriter的。 (您需要关闭所有流套接字以及插座本身。)在重复执行中,的AsyncTask 试图打开一个新的套接字,并最终操作系统用完资源这样做,因为此故障关闭的左右。到新的Socket(...)呼叫抛出一个异常(你可以捕获它),但是客户端遗体。既然你不例外返回后,你再得到一个 NullPointerException异常。我的猜测是,这个 NullPointerException异常是何等的负责应用程序崩溃。 (这确实只是一个猜测。在您发布错误的信息是相当稀疏)

My guess is that the problem arises because you are not properly closing client and printwriter. (You need to close all streams for the socket as well as the socket itself.) On repeated executions, the AsyncTask tries to open a new socket and eventually the OS runs out of resources for doing so because of this failure to close. The call to new Socket(...) throws an exception (which you catch) but then client remains null. Since you don't return after the exception, you then get a NullPointerException. My guess is that this NullPointerException is what's responsible for the app crash. (This really is just a guess; the info in the error you posted is quite sparse.)

试试这个code来代替:

Try this code instead:

public class Asynctask extends AsyncTask<String, Void, Void> {        
    private EditText mTextField;
    protected Void doInBackground(String... messages) {
        String message = messages[0];
        Socket client = null;        
        try {
            client = new Socket(IP_ADDRESS, DEST_PORT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        try {
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage);
        }
            catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (printwriter != null) {
                try {
                    printwriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                printwriter = null;
            }
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
        return null;
    }
}