2

我在我的 PC 上运行了一个简单的套接字服务器,我为 PC 制作了一个客户端来与自己对话,但是我想将它调整为适用于 Android,但它不断崩溃,告诉我 closeChat() 方法有问题,但我无法弄清楚什么。这是我的代码:

    package com.jister13.chattest;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ChatRoom extends Activity
{
    String ip;

    EditText userText;
    EditText chatWindow;
    Button send;

    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String serverIP;
    private Socket connection;

    private Handler handler;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if(extras != null)
        {
            ip = extras.getString("IP");
            serverIP = ip;
        }
        setContentView(R.layout.chat_room);
        setRequestedOrientation(1);

        handler = new Handler();

        userText = (EditText) findViewById(R.id.editText_UserText);
        chatWindow = (EditText) findViewById(R.id.editText_ChatWindow);
        chatWindow.addTextChangedListener(new TextWatcher(){
            public void afterTextChanged(Editable s) {
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Toast.makeText(ChatRoom.this, "Updated", Toast.LENGTH_LONG).show();
            }
        });
        send = (Button) findViewById(R.id.button_Send);
        send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sendMessage("You: " + userText.getText().toString() + "\n");
                userText.setText("");
            }
        });

        startRunning();
    }
    public void startRunning()
    {
        try{
            connectToServer();
            setupStreams();
            whileChatting();
        }catch(EOFException eofException){
            showMessage("\n Chat Session Closed");
        }catch(IOException ioException){
            ioException.printStackTrace();
        }finally{
            closeChat();
        }
    }
    private void connectToServer() throws IOException
    {
        showMessage("Starting Connection...");
        connection = new Socket(InetAddress.getByName(serverIP), 0511);
        showMessage("\n Connection Established: "+connection.getInetAddress().getHostName());
    }
    private void setupStreams() throws IOException
    {
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("\n Chatting streams are now enabled...");
    }
    private void whileChatting() throws IOException 
    {
        ableToType(true);
        do{
            try{
                message = (String) input.readObject();
                showMessage("\n "+message);
            }catch(ClassNotFoundException classNotFoundException){
                showMessage("\n Some Error Occured");
            }
        }while(!message.equals("SERVER - END"));
    }
    private void closeChat()
    {
        showMessage("\n Closing Application...");
        ableToType(false);
        try{
            input.close();
            output.close();
            connection.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    private void sendMessage(String text)
    {
        try{
            output.writeObject("Else: "+text);
            output.flush();
            showMessage("You: "+text+"\n");
        }catch(IOException e){
            chatWindow.append("\n An Error Occured *See ChatRoom.java -> sendMessage()*");
        }
    }
    private void showMessage(final String message)
    {
        handler.post(new Runnable(){
            public void run(){
                chatWindow.append(message);
            }
        });
    }
    private void ableToType(final boolean TorF)
    {
        //userText.setEditable(TorF);
    }
}

http://www.mediafire.com/view/?hr441qalu6b6d7s 这是错误缩小到的图像。

这是整个 PrintStackTrace:

03-08 11:02:43.595: E/AndroidRuntime(3959): FATAL EXCEPTION: main
03-08 11:02:43.595: E/AndroidRuntime(3959): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jister13.chattest/com.jister13.chattest.ChatRoom}: java.lang.NullPointerException
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2088)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.access$700(ActivityThread.java:139)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.os.Looper.loop(Looper.java:137)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.main(ActivityThread.java:4918)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at java.lang.reflect.Method.invokeNative(Native Method)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at java.lang.reflect.Method.invoke(Method.java:511)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at dalvik.system.NativeStart.main(Native Method)
03-08 11:02:43.595: E/AndroidRuntime(3959): Caused by: java.lang.NullPointerException
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.jister13.chattest.ChatRoom.closeChat(ChatRoom.java:115)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.jister13.chattest.ChatRoom.startRunning(ChatRoom.java:82)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at com.jister13.chattest.ChatRoom.onCreate(ChatRoom.java:69)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.Activity.performCreate(Activity.java:5048)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
03-08 11:02:43.595: E/AndroidRuntime(3959):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2052)
03-08 11:02:43.595: E/AndroidRuntime(3959):     ... 11 more
4

1 回答 1

0

简单地说,input就是null。

当它运行时:

public void startRunning()
{
    try{
        connectToServer();
        setupStreams();
        whileChatting();
    }catch(EOFException eofException){
        showMessage("\n Chat Session Closed");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        closeChat();
    }
}

private void connectToServer() throws IOException
{
    showMessage("Starting Connection...");
    connection = new Socket(InetAddress.getByName(serverIP), 0511);
    showMessage("\n Connection Established: "+connection.getInetAddress().getHostName());
}

private void setupStreams() throws IOException
{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n Chatting streams are now enabled...");
}

如果你在input被赋值之前的任何地方出现异常setupStreams(),当你finally调用它时它将为空closeChat()。由于您没有在那里检查 null ,因此它会翻转。

我的建议?在使用它们之前对它们进行空检查:

private void closeChat()
{
    ...
    if(input != null)
        input.close();
    if(output != null)
        output.close();       
    if(connection != null)
        connection.close();
    ....
}
于 2013-03-08T15:50:13.007 回答