-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.

6
  • 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. Commented Apr 17, 2013 at 13:31
  • android.os.NetworkOnMainThreadException that my error but don't really know what it is Commented Apr 17, 2013 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. Commented Apr 17, 2013 at 13:55
  • No problem :p You gotta start somewhere. Commented Apr 17, 2013 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 stackoverflow.com/questions/6343166/… Commented Apr 17, 2013 at 14:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks Santhosh for your answer but it didn't change anything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.