我收到一个错误,表示为Java Null Point Exception。
我试过调试,发现错误只是持久存在。
我认为printwriter
或客户端对象存在问题。
是否有任何初始化错误?
我甚至关闭了我打开的每个插座。
是不是我在其他地方放了几行? 代码是:
package com.example.temp;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
StringBuilder sb = new StringBuilder();
public final static String extra = "com.example.temp.MESSAGE";
protected static final long TIME_DELAY = 5000;
TextView mTextView;
Handler handler=new Handler();
int count =0; String data ="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_id);
messsage= mTextView.getText().toString();
new Asynctask().execute(messsage);
handler.post(updateTextRunnable);
}
Runnable updateTextRunnable = new Runnable() {
public void run() {
if (count < 5) {
WifiManager mainWifiObj;
mainWifiObj =
(WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
List<ScanResult> wifiScanList =
mainWifiObj.getScanResults();
for (ScanResult result : wifiScanList) {
if (result.SSID.equals("Khosla ka Ghosla")) {
sb.append(result.level);
}
count++;
mTextView.setText("getting called " +count + sb);
} else {
}
handler.postDelayed(this, TIME_DELAY);
}
};
public class Asynctask extends AsyncTask<String, Void, Void> {
private static final String IP_ADDRESS = "192.168.0.8";
private static final int DEST_PORT = 4444;
private EditText mTextField;
protected Void doInBackground(String... messages) {
String message = messages[0];
Socket client = null;
try {
client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Write to server.
try {
printwriter =
new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(client !=null){
printwriter.flush();
printwriter.close();
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
}
当我运行当前代码时,错误出现在以下行中:printwriter.write(messsage)
。
你能指导我吗?
提前致谢
答案 0 :(得分:0)
您应该在finally
块中执行此操作。
if (printwriter != null) {
printwriter.flush();
printwriter.close();
}
答案 1 :(得分:0)
您确实需要调试代码。 我可以看到几个可能的问题
String message = messages [0];
您确定该消息是否已正确创建?最有可能的不是问题,因为您没有收到索引超出范围的异常。但无论如何都要另外看。
client = new Socket(IP_ADDRESS,DEST_PORT); //连接到服务器
运行此行代码后“客户端”的价值是多少?它是空的吗?
printwriter = new PrintWriter(client.getOutputStream(), true)
您确定是否已创建了该打印作品?