AsyncTask帮助我

时间:2014-06-06 08:55:30

标签: android android-asynctask

我的AsyncTask中有这个doInBackground()方法:

protected String doInBackground(String ... params){

   try {

         if(!client.isConnected()){
                 client = new Socket("192.168.1.2", 4444);  
         }
         //client = new Socket("192.168.1.2", 4444); 
         oos = new ObjectOutputStream(client.getOutputStream());
         ois = new ObjectInputStream(client.getInputStream());

         oos.writeUTF("LOGIN");
         oos.flush();

         String emailText = email.getText().toString();
         oos.writeUTF(emailText);
         oos.flush();

         String passwordText = password.getText().toString();
         oos.writeUTF(passwordText);
         oos.flush();

         string = ois.readUTF();

   }catch (ConnectException e){
       return "Host not found";
   }catch (IOException e) {
       return "Exception Caught";
   }
   return null;
}

但是当我的应用程序执行此方法时,我收到此错误:

    06-06 11:29:29.224: E/AndroidRuntime(9071): FATAL EXCEPTION: AsyncTask #1
06-06 11:29:29.224: E/AndroidRuntime(9071): java.lang.RuntimeException: An error occured while executing doInBackground()
06-06 11:29:29.224: E/AndroidRuntime(9071):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.lang.Thread.run(Thread.java:841)
06-06 11:29:29.224: E/AndroidRuntime(9071): Caused by: java.lang.NullPointerException
06-06 11:29:29.224: E/AndroidRuntime(9071):     at com.example.social_network.Login$myTask.doInBackground(Login.java:50)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at com.example.social_network.Login$myTask.doInBackground(Login.java:1)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-06 11:29:29.224: E/AndroidRuntime(9071):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-06 11:29:29.224: E/AndroidRuntime(9071):     ... 4 more

和app崩溃。服务器不接收客户端连接 怎么了?

1 个答案:

答案 0 :(得分:2)

在再次创建套接字之前,请尝试检查套接字是否已连接:

try {
    if(client == null) client = new Socket("192.168.1.2", 4444);
    else if(!client.isConnected())
         client = new Socket("192.168.1.2", 4444);  //connect to server
    }
...

请确保您的套接字没有超时。