-2

when I launched my application I have a problem with emulator 4.1 and 4.2 even I have already made ​​the Internet permission, logcat shows this mssage: Error in http connectionandroid.os.NetworkOnMainThreadException ?

    package com.example.eagletracking;

import java.io.InputStream;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.audiofx.BassBoost.Settings;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class GPSTrackingActivity extends Activity implements LocationListener {
    Toast toast;
    boolean isGPSAvaible;
    private LocationManager lm;
    private Location location;
    private static  String key =DBconection.key;
    Calendar currentDate;
    SimpleDateFormat formatter;
    public static double latitude; // latitude                
    public static double longitude; // longitude

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {

                synchronisation();

            }

            else if (msg.what == 1) {
                updateDatabase(location);
            }

        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accueil);

         if (isInternetAvailable(this)) {

             Thread th = new Thread() {

                    public void run() {
                        try {
                            while (true) {
                                Thread.sleep(80000);
                                {
                                    handler.sendEmptyMessage(0);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                th.start();

            }

    }


    public static boolean isInternetAvailable(Context context) {
        boolean isInternetAvailable = false;

        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getActiveNetworkInfo();

            if (networkInfo != null && (networkInfo.isConnected())) {
                isInternetAvailable = true;
            }
        } catch (Exception exception) {
            // Do Nothing
        }

        return isInternetAvailable;
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
         isGPSAvaible = lm.isProviderEnabled (LocationManager.GPS_PROVIDER);
    if (isGPSAvaible)
        {
            abonnementGPS();

        }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private void abonnementGPS() {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
                this);
        if (lm != null) {
            location = lm
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Thread th = new Thread() {

            public void run() {
                try {
                    while (location != null) {
                        Thread.sleep(6000);
                        {
                            handler.sendEmptyMessage(1);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        th.start();
        }
    }

    private void synchronisation() {
        DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
        SQLiteDatabase db = maBaseSQLite.getReadableDatabase();
        Cursor c = maBaseSQLite.getAllRows();
        int col = c.getCount(); // col=0 pas de enregistrement qui
                                // verifie la condition
        if (col == 0) {
            Toast.makeText(GPSTrackingActivity.this, "Pas de donnees ",
                    Toast.LENGTH_LONG).show();
            // effacer le contenue champ login et mot de passe

        } else {
            c.moveToFirst();
            while (c.isAfterLast() == false) {
                // conversion int to string casting
                String id = "" + c.getInt(0);
                String longitude = c.getString(1);
                String latitude = c.getString(2);
                String time = c.getString(3);
                String key_employe = c.getString(4);
                InputStream is = null;
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        4);
                // nameValuePairs.add(new BasicNameValuePair("id",
                // ch1));
                nameValuePairs.add(new BasicNameValuePair("longitude",
                        longitude));
                nameValuePairs
                        .add(new BasicNameValuePair("latitude", latitude));
                nameValuePairs.add(new BasicNameValuePair("time", time));
                nameValuePairs.add(new BasicNameValuePair("key_employe", key_employe));
                c.moveToNext();
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://10.0.2.2:8888/android/synchron.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                } catch (Exception e) {
                    Log.d("connexion_expired",
                            "Error in http connection" + e.toString());
                }
            }

        }

        c.close();
  maBaseSQLite.del();
  maBaseSQLite.close();
    }

    private void updateDatabase(Location location) {
        DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
        SQLiteDatabase DB = maBaseSQLite.getWritableDatabase();

        // maBaseSQLite.onCreate(DB);
        //maBaseSQLite.onUpgrade(DB, 0, 0);
        longitude= location.getLatitude();
        latitude=location.getLatitude();
        currentDate = Calendar.getInstance();
        formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
        maBaseSQLite.addPoint(String.valueOf(longitude),
                String.valueOf(latitude),
                formatter.format(currentDate.getTime()),(key));
        Log.i("insert ", "ok");
        maBaseSQLite.close();
    }

    @Override
    public void onLocationChanged(Location arg0) {


    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }
}
  • You could have just googled. This is a well known problem for beginners and there are dozens of tutorials/answers on how to change the code to fix it... – WarrenFaith May 21 '13 at 14:36

2 Answers2

1

NetworkOnMainThread exception occurs when you are running network related operation on the main UI thread. http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

You use should use a asynctask for this purpose or create your own thread.

You are making a http request on the main ui thread.

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

Check the link above especially the topic under the heading The 4 steps.

Example:

 class TheTask extends AsyncTask<Void,Void,Void>
 {
  protected void onPreExecute()
  {           super.onPreExecute();
            //display progressdialog.
  } 

   protected void doInBackground(Void ...params)
  {  
        //Network related opearaiton. Do not update ui here

        return null;
  } 

   protected void onPostExecute(Void result)
  {     
            super.onPostExecute(result);
            //dismiss progressdialog.
            //update ui
  } 
}
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

As doc says about NetworkOnMainThreadException:

the exception that is thrown when an application attempts to perform a networking operation on its main thread.

So, you're getting this error because you're running your client in the main Thread. To avoid this exception you can use an AsyncTask, Executor or simply using a Thread

edoardotognoni
  • 2,752
  • 3
  • 22
  • 31