-1

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

主.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"/>

感谢你们对我的帮助!<3

4

1 回答 1

2

这些台词是你的罪魁祸首

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

它们之前无法初始化,否则当您尝试对它们调用方法时setContentView()它们会返回null给您一个NPEsetText()

尝试像这样改变它

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

您只能UIUI Thread. 我建议调查AsyncTaskAsyncTask您可以在其中完成所有网络工作,然后以任何其他方法doInBackground()更新您的网络。UI仔细阅读文档。这可能很棘手,但一旦你掌握了它,生活就会容易得多。

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

于 2013-07-24T20:39:55.663 回答