Android 处理NullPointerException,假设这就是问题所在

Android 处理NullPointerException,假设这就是问题所在,android,nullpointerexception,arduino,Android,Nullpointerexception,Arduino,我得到了一个“强制关闭”,我猜它来自一个未处理的异常。下面的代码从我的Android手机向充当Web服务器的Arduino发送HTTP请求。如果Arduino没有响应,例如,如果它没有连接,我想优雅地通知用户,而不是让应用程序意外停止并显示“强制关闭”对话框 在下面的代码中,我在我认为可能发生异常的地方放置了一条注释。这可能是问题所在吗?如果是,我应该如何解决?如果没有,我的代码中还有什么地方出错了 我已经在底部包含了错误消息 public void onClick(View v) {

我得到了一个“强制关闭”,我猜它来自一个未处理的异常。下面的代码从我的Android手机向充当Web服务器的Arduino发送HTTP请求。如果Arduino没有响应,例如,如果它没有连接,我想优雅地通知用户,而不是让应用程序意外停止并显示“强制关闭”对话框

在下面的代码中,我在我认为可能发生异常的地方放置了一条注释。这可能是问题所在吗?如果是,我应该如何解决?如果没有,我的代码中还有什么地方出错了

我已经在底部包含了错误消息

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

尝试检查结果是否不为null,如果失败,请通知用户:

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();
        // ******************************
    }
}

onClick
文件的第70行是什么?如果execute()导致异常,您应该在日志中看到堆栈跟踪。如果您没有在请求中发布任何数据,为什么要使用HttpPost?您从未在HttpPost对象上调用
setEntity()
。哦……我不知道这些数字对应行号……甚至不知道如何在eclipse中查看行号。现在问题解决了,这可能会容易得多。我在执行()时收到显示system.errors的警告。我放置了行
HttpEntity entity=response.getEntity()try
中的code>并捕获NullPointerException。但我想现在的问题是,如果execute()不起作用,那么之后的一切都是无用的。有没有一种可以接受的方法来打破按钮点击事件处理程序?@DavidWasser-我正在使用HttpPost,因为这恰好是我在谷歌搜索中遇到的第一件向服务器发送请求的事情。数据实际上是
?aaa/
,因为我让arduino丢弃请求中的每个字符,直到它到达一个“?”,然后它按顺序处理之后的每个字母,以确定它需要采取什么行动,因此在这种情况下
?aaa/
中的第一个“a”转换为手动控制,第二个“a”转换为“引脚10”,第三个“a”翻译为“On”<代码>?acb/
将翻译为“手动”->“引脚12”->“关闭”。