我的代码用于与java进行简单的聊天。我在第out.println("username,," + username);
行发送用户名时遇到空指针异常,我不知道为什么
package guc.protocols.checkers;
import android.app.Activity;
import android.content.Intent;
//import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class LoginActivity extends Activity implements View.OnClickListener,
Runnable {
static Socket socket;
static BufferedReader in;
static PrintWriter out;
Activity act = this;
String inputMessage;
EditText edit_username;
Button btn_connect;
String username;
boolean exitFromLoop = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
edit_username = (EditText) findViewById(R.id.editText_username);
btn_connect = (Button) findViewById(R.id.button_connect);
btn_connect.setOnClickListener(this);
try {
Thread thread = new Thread(this);
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
if (v == btn_connect) {
username = edit_username.getText().toString();
if (username.equals("")) {
Toast.makeText(getApplicationContext(),
"You must enter your username", Toast.LENGTH_LONG)
.show();
return;
}
out.println("username,," + username);
}
}
@Override
public void run() {
try {
socket = new Socket("10.0.2.2", 5454);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out.println("Hello");
while (!exitFromLoop) {
inputMessage = in.readLine();
if (inputMessage != null) {
Log.i("input", inputMessage);
if (inputMessage.equals("This is the server")) {
// everything is ok - do nothing
} else if (inputMessage.startsWith("username,,")) {
String response = inputMessage.split(",,")[1];
Log.i("input", response);
if (response.equals("yes")) {
exitFromLoop = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Username Available",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(
getApplicationContext(),
ConnectedUsersActivity.class);
startActivity(intent);
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Username Already Taken !!",
Toast.LENGTH_LONG).show();
}
});
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void sendToServer(String message) {
out.println(message);
}
public static String receiveFromServer() {
String received = "";
try {
received = in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
}