-1

I am making an android app.To fetch data from the app server running on my localhost using phpmyadmin, i am using below described php script:

<?php
$host = "localhost";
$db_user = "root" ;
$db_password = "" ;
$db_name = "FCM";

if(isset($_POST["Token"])){
  $con = mysqli_connect($host,$db_user,$db_password,$db_name);

  $sql = "select * from User";

  $res = mysqli_query($con,$sql);

  $result = array();

  while($row = mysqli_fetch_array($res)){
      array_push($result,
          array('UserName'=>$row[0], 'EmailID'=>$row[1], 'UID'=>$row[2]
      ));
  }

  echo json_encode(array("users"=>$result));

  mysqli_close($con);
 }
 ?>

And in my java class, in order to gather the response, I am using Okhttp and below described code:

public void getDataOKHTTP() {
    OkHttpClient client = new OkHttpClient();
    RequestBody body = new FormBody.Builder().add("Token","").build();
    Request request = new Request.Builder().url("http://.........../fcm/test.php").post(body).build();
    System.out.println("@ register a new token ");
    try {
        Response response= client.newCall(request).execute();
        //response.header("Content-Type: application/json");
        myJSON = response.body().string();
    }catch (IOException e){
        e.printStackTrace();
    }
}

But when i run my app, i get,

com.example.apple.fetchdata, PID: 6092 android.os.NetworkOnMainThreadException.

I would be highly obliged if you could help me learn and resolve this problem.

thank you :)

K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
Th3Dark0
  • 132
  • 1
  • 2
  • 10

2 Answers2

1

All network operations has to be done on background thread, you're doing it on a main thread

Alex Shutov
  • 3,217
  • 2
  • 13
  • 11
0

I know it's a late answer for this question. as Th3Dark0 said , All the networking calls must be done on background thread, you should use enque method rather then execute while making a call in OKHttp. You can have a look at here if are you still interested : Networking with OkHttp

islamdidarmd
  • 725
  • 5
  • 19