为什么它在这一行上给我NULLPointerException
outputStream.write(array);
整个主要活动
package com.example.phoneclient;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends Activity {
public Button privateButton;
public Socket CommandSocket,receivingSocket,sendingSocket;
public OutputStream outputStream;
DataOutputStream doDataOutputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
CommandSocket = new Socket("134.129.125.126",62431);
receivingSocket = new Socket("134.129.125.126",52341);
sendingSocket = new Socket("134.129.125.126",42311);
} catch (Exception e) {
// TODO: handle exception
}
privateButton = (Button)findViewById(R.id.private_Mode);
privateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
outputStream = CommandSocket.getOutputStream();
} catch (Exception e) {
// TODO: handle exception
}
String command = "1";
byte[] array = command.getBytes();
System.out.println("byte: "+ array);
try {
outputStream.write(array);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我只想通过单击按钮进行测试,将此“1”发送到服务器C#。我不知道为什么。
答案 0 :(得分:0)
如果你记录了Exception并观察了堆栈跟踪,你会看到NetworkOnMainThreadException
您无法在UI线程上打开网络套接字(在onCreate中),因此您需要创建AsyncTask
或Service
。