【问题标题】:NetworkOnMainThreadException while executing HTTP Request执行 HTTP 请求时出现 NetworkOnMainThreadException
【发布时间】:2015-09-11 15:51:45
【问题描述】:

我搜索了整个互联网,但没有任何答案可以帮助我。

我正在尝试从 MySQL 数据库中获取数据字符串,但只是得到了这个 'andoid.os.NetworkOnMainThreadException' 错误。谁能帮帮我?

这是我的代码:

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

是的,我设置了

&lt;uses-permission android:name="android.permission.INTERNET" /&gt;.

我得到的只是 LogCat 中的错误消息:(

希望你们能帮助我!

感谢您的回答。

【问题讨论】:

  • @user3244807 : 你在线程或 AsyncTask 上调用了“getInformationForBarcode()”吗?
  • @user3244807 : 请不要在主 UI 线程上执行任何网络操作。!!
  • 我不知道您是如何“像整个互联网一样搜索”的,但是您在 Google 中的错误消息会产生大量答案,详细解释正在发生的事情以及原因......

标签: android mysql http-post


【解决方案1】:

当您尝试建立与数据库的连接时,最好在另一个线程中执行此操作以避免应用崩溃,因为此类操作可能需要很长时间。您可以使用AsyncTask 在后台执行这些操作。查看开发者网站了解更多关于任务http://developer.android.com/reference/android/os/AsyncTask.html

的信息

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多