android - 局域网套接字编程 - 获取nullpointer和地址使用异常

时间:2013-08-11 05:23:09

标签: android sockets android-asynctask nullpointerexception

我已经完成了一个应用程序,其中android应用程序将数据发送到java桌面swing应用程序,以及通过wifi使用TCP套接字编程将数据从桌面发送到android。

该申请是酒店厨房订单预订系统

问题描述Dine_Tables类包含代表酒店中每个表的按钮,点击table1按钮,例如它启动 BackgroundServers Asyntask,它运行服务器以接收桌面应用程序数据它还需要Dinein_Tables.javaFood_Customizer.java的活动。

Food_Customizer.java点击提交按钮时,它会启动 ServersendAsyncAction Asyntask,它会将一些数据发送到桌面播放应用程序。

处理后的桌面应用程序向android应用程序发送一些数据,接收数据的android应用程序中运行的服务器再次从 BackgroundServers中的Food_Customizer.javaDinein_Tables.java活动 Asyntask onPostExecute方法。

问题是,当我执行此过程时,由于地址使用而导致应用程序停止两到三次, BackgroundServers中的socket = serverSocket.accept();处的空指针异常 Asyntask

任何人都可以告诉我这个问题的解决方案

Dinein_Tables.java

public class Dinein_Tables extends Activity {
:
:


 table1.setOnClickListener(new OnClickListener() {

                    public void onClick(final View v) {
                        new Handler().postDelayed(new Runnable() {

                            public void run() {

                                        Food_Customizer.BackgroundServers ob = new Food_Customizer().new BackgroundServers(contexts);
                                        ob.execute("");
                                      Intent toAnotherActivity = new Intent(v.getContext(), Food_Customizer.class);
                                      startActivity(toAnotherActivity);
                                      finish();
                            }

                        }, 100L);    

                    }

                });
}

Food_Customizer.java

public class Food_Customizer extends Activity {
:
:
    submit= (Button)findViewById(R.id.submit);
    submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
          pd = ProgressDialog.show(contexts, "Sending to Server...","Please Wait...", true, false);
          new ServersendAsyncAction().execute();
    }
    });
:
:



      /****************************** AsyncTask ********************************************************/

        private class ServersendAsyncAction extends AsyncTask<String, Void, String> {

            /****************************** AsyncTask doInBackground() ACTION ********************************/
            protected String doInBackground(String... args) {


                Socket socket = null;
                DataOutputStream dataOutputStream = null;
                DataInputStream dataInputStream = null;
                boolean flag = true;
                while (flag) /******** If data is send flag turn to be false *******/
                {
                    try {
                        socket = new Socket("192.168.1.74", 4444);
                        dataOutputStream = new DataOutputStream(socket.getOutputStream());
                        dataInputStream = new DataInputStream(socket.getInputStream());
                        dataOutputStream.writeUTF(datastosend);
                        flag = false;
                        } catch (UnknownHostException e) {
                        flag = true;
                        e.printStackTrace();
                        } catch (IOException e) {
                        flag = true;
                        e.printStackTrace();
                        }

                    /******** CLOSING SOCKET *****************/
                    finally {
                        if (socket != null) {
                            try {
                                socket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        /******** CLOSING DATAOUTPUTSTREAM *******/
                        if (dataOutputStream != null) {
                            try {
                                dataOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        /******** CLOSING DATAINPUTSTREAM ********/
                        if (dataInputStream != null) {
                            try {
                                dataInputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                return null;
                /******** returns what you want to pass to the onPostExecute() *******/
            }

            /****************************** AsyncTask onPostExecute() ACTION *********************************/
            protected void onPostExecute(String result) {

            }

        /********************* ENDING OF ASYN TASK CLASS ServersendAsyncAction ***************************/
        }



        public Context con;
            public static ServerSocket serverSocket = null;

        public class BackgroundServers extends AsyncTask<String, Void, String> {

            public BackgroundServers(Context context) {
                con=context;
            }

            /****************************** AsyncTask doInBackground() ACTION ********************************/
            protected  String doInBackground(String... args) {

                Socket socket = null;
                DataInputStream dataInputStream = null;
                DataOutputStream dataOutputStream = null;

                try {
                    serverSocket = new ServerSocket(9999);
                    System.out.println("Listening :9999");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                while (true) {
                    try {
                        socket = serverSocket.accept();
                        dataInputStream = new DataInputStream(
                        socket.getInputStream());
                        dataOutputStream = new DataOutputStream(socket.getOutputStream());
                        System.out.println("ip: " + socket.getInetAddress());
                        String incoming_message=(dataInputStream.readUTF());
                        incoming_message=incoming_message.replace("/", "");
                        String recdatas[]=incoming_message.split("#");
                        if(recdatas[0].equalsIgnoreCase("success"))
                        {
                          DatabaseConnection dbs=new DatabaseConnection(con);
                          int status=dbs.update("UPDATE hotel_pub_tables SET status='occupied' WHERE tableno='"+recdatas[1]+"'");
                          if(status>0)
                                  {
                              tabelstatus=1;
                              //msg.obj="Table status changed!!!";
                              System.out.println("Table status changed!!!");
                              if (true) {
                                    System.out.println("entered 222");

                                               System.out.println(tabelstatus);
                                               if(tabelstatus==1)
                                                {
                                                   System.out.println(tabelstatus); 
                                                   Food_Customizer.pd.dismiss();
                                                   System.out.println("success"); 

                                                }
                                                else if(tabelstatus==2)
                                                {
                                                    Food_Customizer.pd.dismiss();

                                                  Intent intent = new Intent(Food_Customizer.this, Dinein_Tables.class);
                                                  startActivity(intent);
                                                  finish(); 
                                                }

                                }
                          }
                          else
                              tabelstatus=2;
                          dbs.close();
                        }
                        dataOutputStream.writeUTF("Hello!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (socket != null) {
                            try {
                                socket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        if (dataInputStream != null) {
                            try {
                                dataInputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        if (dataOutputStream != null) {
                            try {
                                dataOutputStream.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    }
                             return null;
                }

                /******** returns what you want to pass to the onPostExecute() *******/
            }

            /****************************** AsyncTask onPostExecute() ACTION *********************************/
            @Override
            protected void onPostExecute(String result) {
                System.out.println("eneterd on posttttttttttttttt");
                con.startActivity(new Intent(con, Dinein_Tables.class));
                finish();
                }

            }
        }
        /********************* ENDING OF ASYN TASK CLASS BackgroundServers ***************************/
}

1 个答案:

答案 0 :(得分:1)

很明显,您在端口9999上设置服务器:

serverSocket = new ServerSocket(9999);

但您在端口4444上与服务器连接:

socket = new Socket("192.168.1.74", 4444);

确保连接到正确的端口号,否则它将无法正常工作。希望这会有所帮助。