-1

I am trying to connect to my database on my localhost through my android application. I have created a php file and stored it in my wamp/www/myfolder, when I run it it works fine, so it must be a problem with my android class.

   public void getData(){
    String result ="";
    InputStream isr = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new        HttpPost("http://localhost/testdata/getAllCustomers.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    }catch(Exception e){
        Log.e("log_tag", "Error in http connection");
        resultView.setText("Couldnt connect to database");

I have gone over my code many times but I can't find the problem. I have created two morw try catches in this method that convert the result and the other one parses the data but when I run it the first log appears so it doesn't connect to the database.

P.s I am using eclipse, to I need a plugin for json, I know eclipse IDE supports it.

Laurence Nicolaou
  • 569
  • 2
  • 8
  • 28
  • I get a warning from System.err on HttpResponse response = httpclient.execute(httppost); but I don't understand why and also i get the log I created. – Laurence Nicolaou Apr 17 '13 at 13:31
  • android.os.NetworkOnMainThreadException that my error but don't really know what it is – Laurence Nicolaou Apr 17 '13 at 13:44
  • Thanks Keyser, I know it may be a duplicate but I am new to this site and I don't know how everything really works. Sorry for that. – Laurence Nicolaou Apr 17 '13 at 13:55
  • No problem :p You gotta start somewhere. – keyser Apr 17 '13 at 13:57
  • I have found the solution, Because I am using an android version over 9 I had to use StrictMode in my onCreare method. if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } Answer found from http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Laurence Nicolaou Apr 17 '13 at 14:00
  • Read the comments on that answer, then read my answer :p It's a dangerous workaround. – keyser Apr 17 '13 at 14:02

2 Answers2

0

The loopback address in case of android when you are trying to connect from emulator is 10.0.2.2

i.e instead of localhost use 10.0.2.2

SKK
  • 5,261
  • 3
  • 27
  • 39
0

NetworkOnMainThreadException means that you are attempting to perform a network operation on the main thread, which is forbidden. Simply do it from another thread. This is mainly done by creating an AsyncTask. Here's an example. And here's another one.

It's worth noting that NetworkOnMainThreadException is only thrown for applications targeting the Honeycomb SDK or higher, but the behaviour is always heavily discouraged.

Community
  • 1
  • 1
keyser
  • 18,829
  • 16
  • 59
  • 101