抛出空异常的HTTP请求

时间:2012-12-01 09:35:19

标签: android httpresponse isnull

我有一个创建新连接实例的活动。像这样:

public class myActivity extends Activity {

TextView tv;
ProgressDialog dialog = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.daily_news);

    gestureDetector = new GestureDetector(new SwipeGestureDetector());
    tv = (TextView) findViewById(R.id.tx);
    dialog = ProgressDialog.show(myActivity.this, "","Validating user...", true);
    connection con = new connection(dialog);
    final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");

    runOnUiThread(new Runnable() {
        public void run() {
            tv.setText(str);
            dialog.dismiss();
        }
    });        
}

}

在连接类中我有一个返回null的HttpResponse。像这样:

public class connection {

private HttpPost httppost;
private HttpClient httpclient;
private HttpResponse response;
private ProgressDialog dialog = null;
private String result;

 public connection(ProgressDialog di){
     dialog = di;
 }
public String connect_to_db(String url){

    try{            
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost(url); 
        response=httpclient.execute(httppost);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        result = httpclient.execute(httppost, responseHandler);
    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
    return result;
}

}

为什么连接类中“result”的值为null?

2 个答案:

答案 0 :(得分:1)

这一行:

 final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");

不应该写在onCreate中,而是写在一个单独的线程中=&gt; NetworkOnMainThreadException

对于您的NullPointer,请告诉我们您是否在Manifest中拥有Internet权限,以及响应是否为空。

答案 1 :(得分:0)

可能是因为您正在onCreate方法中进行网络操作。如果你使用的是android2.2,它不会产生任何问题,但如果它是HoneyComb,那么很可能它会导致一些异常,最后你得到空值。将代码移动到onResume()方法。

简化使用

HttpResponse response = httpclient.execute(httppost);

String valueString = EntityUtils.toString(response.getEntity());
int  statusCode = response.getStatusLine().getStatusCode();

打印这些值并查看输出。