-4

I searched like the whole internet but no answer could help me.

I'm trying to get a data string out of an MySQL database but just get this 'andoid.os.NetworkOnMainThreadException' error. Could anyone help me?

Here is my Code:

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

Yes, I set the

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

All i get is the error message in LogCat :(

Hope one of you can help me!

Thanks for answering.

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
  • 2
    possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Emil Sep 11 '15 at 15:53
  • @user3244807 : Did you call 'getInformationForBarcode()' on thread or AsyncTask? – AndiGeeky Sep 11 '15 at 15:54
  • @user3244807 : Please do not perform any network operation on main UI thread.!! – AndiGeeky Sep 11 '15 at 15:55
  • 1
    I don't know how you "searched like the whole internet", but your error message in google yields about a bazillion answers that explain in details what is happening and why... – njzk2 Sep 11 '15 at 16:01

1 Answers1

0

When you try to make connections to database it's better to do that in another thread to avoid app crash because such actions can take long time. You can use AsyncTask to perform those actions in the background. Check out the developers site for more information about the task http://developer.android.com/reference/android/os/AsyncTask.html

SaNtoRiaN
  • 2,212
  • 2
  • 15
  • 25