执行 HTTP 请求时出现 NetworkOnMainThreadException

NetworkOnMainThreadException while executing HTTP Request

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

我正在尝试从 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";
    }          
}

是的,我设置了

<uses-permission android:name="android.permission.INTERNET" />.

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

希望你们中的一个能帮助我!

感谢您的回答。

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