我得到一个“强制关闭”,我猜是来自未处理的异常。我的代码将Android手机的HTTP请求发送给充当网络服务器的Arduino。如果Arduino没有响应,例如如果它没有连接,我想优雅地通知用户这个,而不是让应用程序意外停止并显示“强制关闭”对话框。
在下面的代码中,我发表了一条评论,我认为可能会发生异常。这可能是问题,如果是这样我应该如何解决它?如果没有,我的代码中还有什么东西搞砸了?
我已将LogCat的错误消息包含在底部。
public void onClick(View v) {
// TODO Auto-generated method stub
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
//Send command to turn on outlet 1 "?aaa/"
HttpPost httppost = new HttpPost("http://24.44.23.65:150/?aaa/");
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert response to a string
//*********************************************************************************
// I think the problem might be happening at the next line because if the try/catch
// block above results in an exception, "response" will still be null and there
// won't be an HttpEntity to get.
//*********************************************************************************
HttpEntity entity = response.getEntity();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine())!=null){
sb.append(line);
}
}
catch (IOException e){
e.printStackTrace();
}
String state = sb.toString().trim();
//Test response and update button
if(state.contains("Done")){
//not sure how all of this works but it does
v.getBackground().setColorFilter(0xFFFFFF00, PorterDuff.Mode.MULTIPLY);
Drawable d = outletOneOFF.getBackground();
outletOneOFF.invalidateDrawable(d);
d.clearColorFilter();
((Button) v).setText("Light is On");
outletOneOFF.setText("OFF");
}
else
if(state.contains("Error"))
{
((Button) v).setText("ERROR");
}
}
错误日志:
09-19 17:13:37.746: E/AndroidRuntime(22814): FATAL EXCEPTION: main
09-19 17:13:37.746: E/AndroidRuntime(22814): java.lang.NullPointerException
09-19 17:13:37.746: E/AndroidRuntime(22814): at com.banatwala.aquarium.outlets$1.onClick(outlets.java:70)
09-19 17:13:37.746: E/AndroidRuntime(22814): at android.view.View.performClick(View.java:2532)
09-19 17:13:37.746: E/AndroidRuntime(22814): at android.view.View$PerformClick.run(View.java:9291)
09-19 17:13:37.746: E/AndroidRuntime(22814): at android.os.Handler.handleCallback(Handler.java:587)
09-19 17:13:37.746: E/AndroidRuntime(22814): at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 17:13:37.746: E/AndroidRuntime(22814): at android.os.Looper.loop(Looper.java:150)
09-19 17:13:37.746: E/AndroidRuntime(22814): at android.app.ActivityThread.main(ActivityThread.java:4419)
09-19 17:13:37.746: E/AndroidRuntime(22814): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 17:13:37.746: E/AndroidRuntime(22814): at java.lang.reflect.Method.invoke(Method.java:507)
09-19 17:13:37.746: E/AndroidRuntime(22814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:846)
09-19 17:13:37.746: E/AndroidRuntime(22814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
09-19 17:13:37.746: E/AndroidRuntime(22814): at dalvik.system.NativeStart.main(Native Method)
09-19 17:13:37.806: D/dalvikvm(22814): GC_CONCURRENT freed 343K, 49% free 2903K/5639K, external 0K/0K, paused 7ms+3ms
答案 0 :(得分:0)
尝试检查结果是否为空,如果失败则通知用户:
public void onClick(View v) {
// TODO Auto-generated method stub
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
//Send command to turn on outlet 1 "?aaa/"
HttpPost httppost = new HttpPost("http://24.44.23.65:150/?aaa/");
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert response to a string
// Try this:
if(response != null) {
HttpEntity entity = response.getEntity();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine())!=null){
sb.append(line);
}
}
catch (IOException e){
e.printStackTrace();
}
String state = sb.toString().trim();
//Test response and update button
if(state.contains("Done")){
//not sure how all of this works but it does
v.getBackground().setColorFilter(0xFFFFFF00, PorterDuff.Mode.MULTIPLY);
Drawable d = outletOneOFF.getBackground();
outletOneOFF.invalidateDrawable(d);
d.clearColorFilter();
((Button) v).setText("Light is On");
outletOneOFF.setText("OFF");
}
else
if(state.contains("Error"))
{
((Button) v).setText("ERROR");
}
} else {
// ******************************
// notify the User that the Arduino is not available
// like
Toast.makeText(this, "Cannot connect to the Arduino!", Toast.LENGTH_LONG).show();
// ******************************
}
}