2

Hello , i'm trying to register a user from an android application. I installed Xampp, I created my database, I made a php page that will be called to save the data in the database.and when I put the url http://192.168.xx/ah_login_api/ to acces to my php file .An Exception type: "android.os.NetworkOnMainThreadException" at $ android.StrictMode AndroidBlockGuardPolicy.onNetwork

I do not understand where does the problem!

fdreger
  • 12,264
  • 1
  • 36
  • 42
mzpx
  • 39
  • 1
  • 2

2 Answers2

1

You need to use an AsyncTask to do all your network operations.

Your network operation can take a lot of time and the UI would get unresponsive if it is done on the main UI thread. And if your UI freezes for a long time, the app might get killed by the OS.

Thus Android 4+ makes it mandatory to use a background thread to perform network operations.

Put the code to do the network activity inside doInBackground() and all the AsyncTask using execute().

Here is how your AsyncTask would look like :

private class MyAsyncTask extends AsyncTask<String, Integer, Void> {
     protected void doInBackground() {
        sendEmail();
 }

 protected void onProgressUpdate() {
    //called when the background task makes any progress
 }

  protected void onPreExecute() {
     //called before doInBackground() is started
 }
 protected void onPostExecute() {
     //called after doInBackground() has finished 
 }
  }

And you can call it anywhere using new MyAsyncTask().execute("");

Swayam
  • 16,294
  • 14
  • 64
  • 102
0

You need to use an AsyncTask for newtwork operations , because running long operations on the main thread can make lags to your ui or even make it non responsive .

Although it is best to use AsyncTask , you can also just use an another thread

Like :

Thread xamp = new Thread(){

public void run(){
//Your network operation here
}

};
xamp.start();

Refs : http://developer.android.com/reference/android/os/AsyncTask.html

CartMan
  • 37
  • 7