0

我得到一个“强制关闭”,我猜这是一个未处理的异常。下面的代码从我的 Android 手机向充当网络服务器的 Arduino 发送 HTTP 请求。如果 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
4

1 回答 1

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();
        // ******************************
    }
}
于 2012-11-13T09:54:20.243 回答