尝试创建PC到模拟器聊天应用程序,获取输出流关闭空指针异常

时间:2015-08-29 22:01:24

标签: android sockets nullpointerexception stream objectoutputstream

这是代码:

private EditText userText;
private Button bsend;
private TextView chatwindow;
private Socket connection;
private ObjectOutputStream output;
private ObjectInputStream input;
private String serverIP="10.0.2.2";
private String message="";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    userText = (EditText) findViewById(R.id.userText);
    userText.setEnabled(false);
    chatwindow=(TextView) findViewById(R.id.chatwindow);
    bsend = (Button) findViewById(R.id.bsend);
    startRunning();
    bsend.setOnClickListener(

            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendMessage(userText.getText().toString());
                    userText.setText("");

                }
            }
    );



}
public void startRunning(){

    try{
        connectToServer();
        setupStreams();
        chatUp();
    }
    catch(EOFException e){
        showMessage("\nServer Closed The Connection\n");
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        closeSystems();
    }


}
public void connectToServer()throws IOException{
    showMessage("\n********Connecting to Server......*********\n");
    connection = new Socket(InetAddress.getByName(serverIP),5000);
    showMessage("\n********Connection Successful*********\n");

}
public void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n***********Streams Setup Successfully***************\n");
}
public void chatUp() throws IOException{
    ableToType(true);
    showMessage("\nChatting can now Begin......\n");
    do{

        try {
            message = (String) input.readObject();
            sendMessage("\n"+message);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
    while(!message.equals("SERVER - END"));
}
public void  closeSystems() {
    ableToType(false);
    try{

        output.close();
        input.close();
        connection.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }

}
public void sendMessage(final String m){
    try{
        output.writeObject(m);
        output.flush();
    }
    catch(IOException e){
        e.printStackTrace();
    }
}
public void showMessage(final String m){


    chatwindow.append(m);

}
public void ableToType(final boolean tof){

    userText.setEnabled(tof);

}

尝试使用ip 10.0.2.2将仿真器连接到计算机。 这只发生在android系统上。我在eclipse中测试了类似的代码并没有问题。 欣赏它,如果有人能告诉我为什么我在output.close()得到Null指针异常 感谢

0 个答案:

没有答案