Th3Dark0 Th3Dark0 - 2 years ago 66
Android Question

Encountering android.os.NetworkOnMainThreadException while fetching data from a PHP script using Okhttp

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:

$host = "localhost";
$db_user = "root" ;
$db_password = "" ;
$db_name = "FCM";

$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('UserName'=>$row[0], 'EmailID'=>$row[1], 'UID'=>$row[2]

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


And in my java class, in order to gather the response, I am using
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){

But when i run my app, i get,, PID: 6092

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

thank you :)

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download