Android Chat App崩溃了

时间:2013-07-24 20:38:13

标签: android

我和一些朋友用Java编写了一个聊天程序,现在我们想制作一个Android-App。我今天开始只使用基本功能。当我试图运行它时,它会崩溃 “不幸的是你的应用程序崩溃了”或类似的东西。

Main.java

package com.Linkr.linkrandroid;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

import static com.Linkr.linkrandroid.R.*;

public class Chat extends Activity {

    String username;
    Socket sock;
    BufferedReader reader;
    PrintWriter writer;
    ArrayList<String> userList = new ArrayList();
    //Boolean isConnected = false;
    TextView chatTextArea = (TextView) findViewById(R.id.chatTextArea);
    TextView inputTextArea = (TextView) findViewById(id.inputTextArea);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_chat);
        this.setTitle("Linkr");

    }


public class IncomingReader implements Runnable{

    public void run() {
        String[] data;
        String stream, done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat";

        try {
            while ((stream = reader.readLine()) != null) {

                data = stream.split(":");

                if (data[2].equals(chat)) {

                    chatTextArea.append(data[0] + ": " + data[1] + "\n");
                    //chatTextArea.setCaretPosition(chatTextArea.getDocument().getLength());

                } else if (data[2].equals(connect)){

                    //chatTextArea.removeAll();
                    //userAdd(data[0]);

                } else if (data[2].equals(disconnect)) {


                    //userRemove(data[0]);

                } else if (data[2].equals(done)) {


                    /*usersList.setText("");
                    writeUsers();
                    userList.clear();
                    */

                }

            }
        }catch(Exception ex) {
        }
    }
}

public void ListenThread() {
    Thread IncomingReader = new Thread(new IncomingReader());
    IncomingReader.start();
}
public void userAdd(String data) {
    userList.add(data);

}

public void userRemove(String data) {
    chatTextArea.append(data + " has disconnected.\n");

}

public void writeUsers() {
    String[] tempList = new String[(userList.size())];
    userList.toArray(tempList);
    /*for (String token:tempList) {

        usersList.append(token + "\n");

    }
    */

}

public void sendDisconnect() {

    String bye = (username + ": :Disconnect");
    try{
        writer.println(bye); // Sends server the disconnect signal.
        writer.flush(); // flushes the buffer
    } catch (Exception e) {
        chatTextArea.append("Could not send Disconnect message.\n");
    }

}
public void Disconnect() {

    try {
        chatTextArea.append("Disconnected.\n");
        sock.close();
    } catch(Exception ex) {
        chatTextArea.append("Failed to disconnect. \n");
    }
    isConnected = false;
    //usersList.setText("");

}
private void onClickButton(View view) {
    String nothing = "";
    if ((inputTextArea.getText()).equals(nothing)) {
        inputTextArea.setText("");
        inputTextArea.requestFocus();
    } else {
        try {
            writer.println(username + ":" + inputTextArea.getText() + ":" + "Chat");
            writer.flush(); // flushes the buffer
        } catch (Exception ex) {
            chatTextArea.append("Message was not sent. \n");
        }
        inputTextArea.setText("");
        inputTextArea.requestFocus();
    }

    inputTextArea.setText("");
    inputTextArea.requestFocus();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.chat, menu);
    return true;
}

}

acitivity_chat.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".Chat">
android:text = "Linkr"

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/inputTextArea"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/onClickButton"/>

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/onClickButton"
        android:layout_below="@+id/chatTextArea"
        android:layout_alignRight="@+id/chatTextArea"/>

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/chatTextArea"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_above="@+id/inputTextArea"
        android:layout_alignParentRight="true"/>

谢谢你的帮助! &LT; 3

1 个答案:

答案 0 :(得分:2)

这些行是你的罪魁祸首

TextView chatTextArea = (TextView) findViewById(R.id.chatTextArea);
TextView inputTextArea = (TextView) findViewById(id.inputTextArea);

他们无法在setContentView()之前初始化,或者当您尝试在null上调用方法时,他们会返回NPE给您一个setText()

尝试改变它

TextView chatTextArea; 
TextView inputTextArea; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_chat);
    chatTextArea; = (TextView) findViewById(R.id.chatTextArea);
    inputTextArea; = (TextView) findViewById(id.inputTextArea);
    this.setTitle("Linkr");

此外,您似乎正在尝试更新后台线程上的UI元素

chatTextArea.append

您只能更新UI上的UI Thread。我建议调查AsyncTask。使用AsyncTask,您可以在doInBackground()中执行所有网络内容,然后使用其他任何方法更新UI。仔细阅读文档。这可能很棘手,但一旦掌握了它,生活就会轻松得多。

此外,在SO上发帖时,如果您的应用程序崩溃后发布了logcat,因为这通常会让人们更容易提供帮助。