Android 执行HTTP请求时出现NetworkOnMainThreadException
我像整个互联网一样搜索,但没有任何答案可以帮助我 我试图从MySQL数据库中获取一个数据字符串,但只得到了这个“andoid.os.NetworkOnMainThreadException”错误。有人能帮我吗 这是我的密码:Android 执行HTTP请求时出现NetworkOnMainThreadException,android,mysql,http-post,Android,Mysql,Http Post,我像整个互联网一样搜索,但没有任何答案可以帮助我 我试图从MySQL数据库中获取一个数据字符串,但只得到了这个“andoid.os.NetworkOnMainThreadException”错误。有人能帮我吗 这是我的密码: public String getInformationForBarcode(String barcode) { try { HttpClient httpClient = new DefaultHttpClient(); Http
public String getInformationForBarcode(String barcode) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.example.com"); // Yes, i changed this in live code to my url with data in it
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost,
responseHandler);
return response.trim();
} catch (Exception e) {
System.out.println("ERROR : " + e.toString());
return "error";
}
}
是的,我设置了
我得到的只是LogCat中的错误消息:
希望你们中的一个能帮助我
感谢您的回答。当您尝试连接到数据库时,最好在另一个线程中进行连接,以避免应用程序崩溃,因为此类操作可能需要很长时间。您可以使用AsyncTask在后台执行这些操作。查看开发人员站点以了解有关该任务的更多信息可能重复的@user3244807:您是否在线程或异步任务上调用了“getInformationForBarcode”?@user3244807:请不要在主UI线程上执行任何网络操作。!!我不知道你是如何像整个互联网一样搜索的,但是你在谷歌上的错误信息会产生大量的答案,详细解释发生了什么以及为什么。。。