我正在使用一个类来使用HTTPPOST&通过php/json从数据库中获取数据并将其转换为字符串。
问题是我LogCat中的"Error in http connection android.os.NetworkOnMainThreadException"
。我正在模拟器上测试这一点,并使用正确的端口地址。我知道这一点是因为端口在应用程序的其他部分(从Localhost加载HTML)中运行良好。如果我在桌面浏览器中运行php文件,它运行得很好。我也知道权限在mySQL 10.0.2.2&php登录文件中的用户集。
所以我的问题是:有人遇到过同样的问题吗?如果有,你有没有弄清楚问题是什么,或者我还应该寻找什么?
谢谢你的帮助!
public void loadQuery(String p) {
String qO = getIntent().getStringExtra("QUERY_ORDER");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost("http://10.0.2.2/Andaero/php/" +
// p + qO + ".php");
//Hard coded the php link to make sure -->
HttpPost httppost = new HttpPost(
"http://10.0.2.2/Andaero/php/regulatory_list_ASC.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "'n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "'n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
setListAdapter(new QueryAdapter(this, result));
}
您可能正在对应用程序的主线程执行网络操作(这是引发异常的常见原因)。
你永远不应该那样做。主线程应该只用于用户交互,所有网络交互都应该卸载到辅助线程(例如,使用AsyncTask)。
欲了解更多信息,请阅读:http://developer.android.com/guide/practices/design/responsiveness.html