Pergunta

I'm having some problems when I try to call a php function (method get) from an android app. The code in the app is:

 try {
        String link="http://localhost?name=" + name;
        System.out.println(link);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(link);
        HttpResponse response = httpclient.execute(httpget);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {                    
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        Log.v("My Response :: ", result);


  }catch(Exception e){
     Log.i("error", ("Exception: " + e.getMessage()));
  }

and in the server side the php code is:

  <?php
  $con=mysqli_connect("localhost","root","","emergency");
  if (mysqli_connect_errno($con))
  {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $name = $_GET['name'];


   $sql = "INSERT INTO data (name, age, cell, sex, status, ocupation, origin, residence, contactName, phone1, phone2, latitude, longitude) values ('".$name."',23,'22256602','true','soltero','empleado','mexicano','puebla','Marua','552786','','19.038306','-98.20621')";

   echo $sql . "</br></br></br>";
   if (!mysqli_query($con,$sql))
   {
      die('Error: ' . mysqli_error($con));
   }
   echo "1 record added";

   mysqli_close($con);
   ?>

The problem is I've tryed different ways but still returns me a null exception.. What can I do? :s Thak you very much!!

Foi útil?

Solução 2

You should not establish network connections from the UI thread. That is why you got the Exception:

 Exception: android.os.NetworkOnMainThreadException

You should move your code that connects to your server into a background thread, for example with an AsyncTask.

One of the main reasons why this should be done asynchronously is to avoid a frozen UI.

Outras dicas

localhost is pointing to your local android device. If you want to connect your computer PC set it's IP address instead of localhost for example http://192.168.1.1?name=

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top