1

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

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;
}

}

为什么连接类中“结果”的值为空?

4

2 回答 2

1

这一行:

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

不应该写在 onCreate 中,而是写在单独的线程中 => NetworkOnMainThreadException

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

于 2012-12-01T09:43:06.780 回答
0

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

为了简单使用

HttpResponse 响应 = httpclient.execute(httppost);

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

打印这些值并查看输出。

于 2012-12-01T09:45:26.597 回答