Crash of gps tracking applicaiton

Put problem concerning MapActivities, MapViews, Overlays and GPS in this forum.

Crash of gps tracking applicaiton

Postby skodik » Wed Jun 08, 2011 7:56 pm

Hi everyone,
I am working on my bachelor project to school. I have somewhere in my code fatal error. When i debug on emulator, everything is ok and application works(track movement) quite fine. But when i debug on a device application crashes when exceeded MIN_FIX_COUNT. I dont know how to handle this exception, i have tried to use try catch block, but without any change :( I would like to ask you if someone could take a look at my code and tell what iam doing wrong. Thank you. Here is code of my main activity
Code: Select all
package com.vyhlidal.GPStracker;
import java.text.DecimalFormat;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.content.SharedPreferences;

public class GPSTracker extends Activity {
   public static final String UPDATE_SERVICE_BROADCAST = "com.vyhlidal.GPStracker.Action.Update";
   public static final String START_RECORD = "start";
   public static final String STOP_RECORD = "stop";
   public static final String PAUSE_RECORD = "pause";
   public static final String CONTINUE_RECORD = "continue";
   public static final String DROP_DATABASE ="dropDatabase";
   public static final String LAST_RECORD = "lastRecord";
   public static final String PREFERENCE_FILENAME = "TrackerPreferences";
   /*      Preference names    */
   public static final String IS_RECORDING = "isRecording";
   public static final String IS_PAUSE = "isPause";
   public static final String START_TIME = "startTime";
   public static final String MAX_SPEED = "maxSpeed";
   public static final String LONGITUDE = "Longitude";
   public static final String LATITUDE = "Latitude";
   public static final String IN_KM = "inKM";
   public static final String DISTANCE = "Distance";
   
    public TextView Longtitude;
    public TextView Latitude;
    public TextView Vzdalenost;
    public TextView NadmVyska;
    public TextView AktulniR;
    public TextView MaximalniRychlost;
    public TextView PrumernaRychlost;
   
    private int ErrorValue = -1;
    double ProslaVzdalenost = 0;
    private ToggleButton EneableZaznam;
    private Button Pause;
    private Button Exit;
    private float maxSpeed = 0;
    private double lastLatitude = 0;
    private double lastLongitude = 0;
    private long startTime = 0;
    private boolean inKm = false;
    private boolean isRecording = false;
    private boolean isPause = false;

    BroadcastReceiver MyRecieverTracker;
   
   
     /** Called when the activity is first created. */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);       
         InitializeReciever();
         startMyService();             
         InitializeGui();
       
         Log.v("Tracker", "Dokonceno vytvoreni Trackeru");
         
         loadSharedPreferences();
         Pause.setClickable(false);
     }
     
     
     private void EneableReciever()
     {
        IntentFilter filter = new IntentFilter();
        filter.addAction(TrackerService.LOCATION_BROADCAST);
        registerReceiver(MyRecieverTracker, filter);
     }
     private void DisableReciever()
     {
        unregisterReceiver(MyRecieverTracker);       
     }
     @Override
     public void onStart()
     {
        Log.v("Tracker", "On start - aktivita do popředí");
       
        super.onStart();
       
     }
     
     @Override
     public void onResume()
     {
        Log.v("Tracker", "On resume - aktivita do popředí");
        EneableReciever();
        loadSharedPreferences();
        super.onResume();
     }
     
     @Override
     public void onDestroy()
     {
        DisableReciever();
        Log.v("Tracker", "On Destroy - zničeno");
        super.onDestroy();
       
     }
     @Override
     public void onPause()
     {
        Log.v("Tracker", "On Pause - aktivita do popředí");
        DisableReciever();
        super.onPause();
        
     }
     @Override
     public void onStop()
     {
        Log.v("Tracker", "On Stop - aktivita do pozadi");
        DisableReciever();
        super.onStop();
     }
     
     private void InitializeGui()
     {
        Vzdalenost = (TextView) findViewById(R.id.vzadlenostView);
         EneableZaznam = (ToggleButton)findViewById(R.id.zaznamButton);
         EneableZaznam.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View v) {
            if(isGpsEnabled()){
            if(EneableZaznam.isChecked())
            {
               RemoveValuesAfterEnd();
               MakeBroadcastToService(START_RECORD, 2000);
               Pause.setClickable(true);
               Toast.makeText(getApplicationContext(), "Spuštěn záznam", Toast.LENGTH_SHORT).show();
               isRecording = true;
               Log.v("GPS Tracker", "Vyslan broadcast po kliknuti na Start/stop");   
            }
            else
            {
               MakeBroadcastToService(STOP_RECORD, 0);
               Pause.setClickable(false);
               Toast.makeText(getApplicationContext(), "Záznam zastaven", Toast.LENGTH_SHORT).show();
               isRecording = false;
               Log.v("GPS Tracker", "Vyslan broadcast po kliknuti na Start/stop");
               RemoveValuesAfterEnd();
               
            }
            
         }else{
            EneableZaznam.setChecked(false);
         }
         }

         
      });
         
        Exit = (Button)findViewById(R.id.buttonExit);
        Exit.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View arg0) {
            // TODO Auto-generated method stub
            try {
               stopMyService();
               finalize();
            } catch (Throwable e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            
         }
      });
       
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Vymazat databazi");
      builder.setMessage("Opravdu chcete vymazat všechna data?")
          .setCancelable(false)
          .setPositiveButton("Ano", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                 MakeBroadcastToService(DROP_DATABASE, 0);
                 RemoveValuesAfterEnd();
              }
          })
          .setNegativeButton("Ne", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                   dialog.cancel();
              }
          });
      final AlertDialog alert = builder.create();
   
         final Button Vymaz = (Button)findViewById(R.id.Button02);
         Vymaz.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View v) {
            alert.show();
         }
      });
                 
         Pause = (Button)findViewById(R.id.Pause);
         Pause.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View v) {
            if(isPause)
            {
               MakeBroadcastToService(CONTINUE_RECORD, 1000);
               Toast.makeText(getApplicationContext(), "Záznam pokračuje", Toast.LENGTH_SHORT).show();
               isRecording = true;
               isPause = false;
               Log.v("GPS Tracker", "Vyslan broadcast po kliknuti na pauzu");
               
            }else{
               MakeBroadcastToService(PAUSE_RECORD, 1000);
               Toast.makeText(getApplicationContext(), "Záznam pozastaven", Toast.LENGTH_SHORT).show();
               isRecording = false;
               isPause = true;
               Log.v("GPS Tracker", "Vyslan broadcast po kliknuti na pauzu");
            
            }
         }
      });
       
     }
     
     private boolean isGpsEnabled()
     {
         final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

           if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
           {              
                     final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                     builder.setMessage("Nemáte zapnutý GPS přijímač, prosím zapněte GPS přijímač v nastavení.")
                            .setCancelable(false)
                            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {                        
                        @Override
                        public void onClick(DialogInterface dialog, int arg1) {
                           dialog.cancel();                           
                        }
                     });
                            
                     final AlertDialog alert = builder.create();
                     alert.show();
                     return false;
           }else{
              return true;
           }
      }
     private void updateSharedPreference()
     {
        SharedPreferences myPrefs = this.getSharedPreferences(PREFERENCE_FILENAME, MODE_WORLD_READABLE);
         SharedPreferences.Editor prefsEditor = myPrefs.edit();
         prefsEditor.putBoolean(IS_RECORDING, isRecording);
         prefsEditor.putBoolean(IS_PAUSE, isPause);
         prefsEditor.putBoolean(IN_KM, inKm);
         prefsEditor.putFloat(MAX_SPEED, maxSpeed);
      //   prefsEditor.putDouble(LONGITUDE, lastLongitude);
      //   prefsEditor.putDouble(LATITUDE, lastLatitude);
         prefsEditor.putLong(START_TIME, startTime);
         prefsEditor.putLong(DISTANCE, (long)ProslaVzdalenost);
         
         prefsEditor.commit();
         Log.v("Data zalohovana", "Dokonceno zalohovani dat.");
       
     }
     
     private void loadSharedPreferences()
     {/*
        double tmpLat, tmpLon =0;
        SharedPreferences myPrefs = this.getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE);
        isRecording = myPrefs.getBoolean(IS_RECORDING, false);
        isPause = myPrefs.getBoolean(IS_PAUSE, true);
        inKm = myPrefs.getBoolean(IN_KM, false);
        startTime = myPrefs.getLong(START_TIME, 0);
       
        maxSpeed = myPrefs.getFloat(MAX_SPEED, 0);
        /*    souradnice   *//*
        tmpLon = myPrefs.getFloat(LONGITUDE, 0);
        tmpLat = myPrefs.getFloat(LATITUDE, 0);
        ProslaVzdalenost = myPrefs.getLong(DISTANCE, 0);
       
        if(isRecording || isPause)
        {
           ToggleButton tg = (ToggleButton) findViewById(R.id.zaznamButton);
           tg.setChecked(true);
        }
       
        Log.v("Nahrana data", "Dokonceno nahrati dat ze zalohy");*/
        //TODO dodelat zobrazeni dat po znovanacteni aplikace - obnoveni do stavu ve kterem byla ukoncena
       
     }
   
         
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu, menu);
         Log.v(GPSTracker.class.getSimpleName(), "Menu vytvoreno.");
         return true;
     }

     
     public boolean onOptionsItemSelected(MenuItem item)
     {
        updateSharedPreference();
        super.onOptionsItemSelected(item);
        
        switch(item.getItemId()){
        
        case(R.id.mapa):
           //mapa
           Intent myIntent2 = new Intent(this, MyMap.class);
      startActivity(myIntent2);
           
           //Toast.makeText(this, "Zmacknuto tlaco", Toast.LENGTH_SHORT);   
           return true;
        case(R.id.nastaveni):
           Intent myIntent3 = new Intent(this, MyPreferences.class);
         startActivity(myIntent3);
           
           return true;
        case(R.id.export):
           //Toast.makeText(this, "Zmacknuto tlaco", Toast.LENGTH_SHORT);   
           Intent myIntent4 = new Intent(this, ExportFile.class);
           //TODO doplnit kod k resultu activity, pri spusteni activity zastavit veskere zaznamy
         startActivity(myIntent4);
           return true;
        case(R.id.item05):
           //Toast.makeText(this, "Zmacknuto tlaco", Toast.LENGTH_SHORT);   
           Intent myIntent5 = new Intent(this, Navigation.class);
         startActivity(myIntent5);
           return true;
        }
        //return false if menu item was not handled
        return false;
     }
     
     private void InitializeReciever()
     {
        IntentFilter filter = new IntentFilter();
        filter.addAction(TrackerService.LOCATION_BROADCAST);

     MyRecieverTracker = new BroadcastReceiver()
     {
        @Override
        public void onReceive(Context context, Intent intent)
        {
           if(intent.getAction().equals(TrackerService.LOCATION_BROADCAST))
           {
              Log.v("Gps Tracker", "Prijat loacation broadcast od service.");
                                         
              if(isRecording)
              {
                 double lat=0, lon=0, alt =0;
                 float speed=0, bearing =0;
                 long time =0;
                 lat = intent.getDoubleExtra("latitude", ErrorValue);
                 lon = intent.getDoubleExtra("longitude", ErrorValue);
                 alt =  intent.getDoubleExtra("altitude",ErrorValue);
                 speed =  intent.getFloatExtra("speed", ErrorValue);
                 time = intent.getLongExtra("time", ErrorValue);
                 bearing = intent.getFloatExtra("bearing", ErrorValue);
                 updateGuiIfRecord(true,lat, lon, alt, speed, time, bearing);
              }//else{ updateGuiIfRecord(true,lat, lon, alt, speed, time, bearing);}
           }       
        }
     };     

     EneableReciever();
     }

     public void startMyService()
     {
        startService(new Intent(this, TrackerService.class));
        Log.v("Tracker", "Service spusten.");
     }
     
     @SuppressWarnings("unused")
   private void stopMyService()
     {
        stopService(new Intent(this, TrackerService.class));
     }
     private void RemoveValuesAfterEnd()
     {
        lastLongitude = 0;
        lastLatitude = 0;
        startTime = 0;
        maxSpeed = 0;
        ProslaVzdalenost = 0;
     }
     
     private void MakeBroadcastToService(String action, int updateInterval)
     {       
        Intent i = new Intent(UPDATE_SERVICE_BROADCAST);
        i.putExtra(action, updateInterval);
        sendBroadcast(i);
        Log.v("Gps Tracker", "broadcast do service");
     }
     private void updateGuiIfRecord(boolean isRecording, double lat, double lon, double alt, float speed, long time, float bearing)
     {
        Longtitude = (TextView) findViewById(R.id.longtitude);
        Latitude = (TextView) findViewById(R.id.latitude);
        Vzdalenost = (TextView) findViewById(R.id.vzadlenostView);
        NadmVyska = (TextView) findViewById(R.id.NadmVyskaViewData);
        AktulniR = (TextView) findViewById(R.id.AktualniRychlostData);
        MaximalniRychlost = (TextView)findViewById(R.id.TextViewMaxSpeed);
        PrumernaRychlost = (TextView) findViewById(R.id.TextView05);
        
        if(isRecording)
        {
           if(lastLatitude == 0 && lastLongitude ==0)
              {                 
                 lastLatitude = lat;
                 lastLongitude = lon;
                 ProslaVzdalenost = 0;
              }
              else{
                 double tmpDistance = CalculateDistanceHaversine((float)lastLatitude, (float)lastLongitude, (float)lat, (float)lon);
                 ProslaVzdalenost += tmpDistance;
                 ProslaVzdalenost = roundTwoDecimals(ProslaVzdalenost);
                 String vzdalenost = String.valueOf(ProslaVzdalenost);
                 Vzdalenost.setText(vzdalenost +" km" );   
                 //nastavim predchozi
                 lastLatitude = lat;
                 lastLongitude = lon;
              }
          
              if(startTime == 0)
              {
                 startTime = time;//ms na sekundy
              }
              else
              {
                 long actTime = time;//ms na sekundy
                 long moveTime = actTime - startTime;//ziskam dobu pohybu v sekundach
                 double avgSpeed = roundTwoDecimals(CalculateAvgSpeed(moveTime, ProslaVzdalenost));
                 String avgS = String.valueOf(avgSpeed);
                 PrumernaRychlost.setText(avgS + " km/h");
                                  
              }
        }
       
       float rych = speed;
       //rych = randomNumber(2, 15);

       if(rych > maxSpeed)
       {
          maxSpeed = rych;
          String maxRychlost = String.valueOf(maxSpeed);
          MaximalniRychlost.setText(maxRychlost);
          
       }
       
       double alti = alt;
       //alt = randomNumber(100, 250);
       
       String tmpLat = Location.convert(lat, 1);
       String tmpLon = Location.convert(lon, 1);
       tmpLat.replace(':', '°');
       tmpLon.replace(':', '°');
                        
       Longtitude.setText(tmpLon);
       Latitude.setText(tmpLat);
       NadmVyska.setText(String.valueOf(alti));
       AktulniR.setText(String.valueOf(speed));
     }
     
   
     public static int randomNumber(int min, int max) {
         return min + (new Random()).nextInt(max-min);
}
     
     private double CalculateAvgSpeed(long time, double distance) {
        double result = (distance*1000)/time;//v metrech za sekundu
        result = result*3.6;//km/h
        result = roundTwoDecimals(result);
      return result;
   }
   
     private double roundTwoDecimals(double d) {
         DecimalFormat twoDForm = new DecimalFormat("#.##");
         return Double.valueOf(twoDForm.format(d));
    }
     
     
     public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
           double earthRadius = 3958.75;
           double dLat = Math.toRadians(lat2-lat1);
           double dLng = Math.toRadians(lng2-lng1);
           double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                      Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                      Math.sin(dLng/2) * Math.sin(dLng/2);
           double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
           double dist = earthRadius * c;

           return dist;
           }
     private double CalculateDistanceHaversine(float lata, float lnga,float latb, float lngb)
     {
        float radius = (float) 6371;//km
        double distance = 0;
        double dLat = Math.toRadians(latb - lata);
        double dLon = Math.toRadians(lngb - lnga);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lata)) * Math.cos(Math.toRadians(latb)) * Math.sin(dLon/2) * Math.sin(dLon/2);
               
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt((1-a)));
        distance = radius * c;
         distance = roundTwoDecimals(distance);//metry
       
         return distance;
     }

Here is code of my service. This service is used for getting location updates, store them into database and send them thru sendBroadcast(intent) to main activity. I think, that this error is somewhere in this code.
Code: Select all
package com.vyhlidal.GPStracker;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import android.widget.TextView.SavedState;

public class TrackerService extends Service implements LocationListener{
    public static final String LOCATION_BROADCAST = "com.vyhlidal.GPStracker.Action.Send";
    public static final String DATA_BROADCAST = "com.vyhlidal.GPStracker.Action.DataSend";
    public static final String RECORD = "Record";
    public static final String RECORD_ID = "RecordId";
    public static final String UPDATE_TIME = "UpdateTime";
   
    public boolean record = false;
   private int recordId = 0;
   public int UpdateTime = 3000;//in milliseconds
   private MyDatabaseManager DbManager;
   private LocationManager locMgr;
   BroadcastReceiver MyRecieverService;
   
   private double Latitude = 0;
   private double Longitude = 0;
   private double altitude = 0;
   
   private void MakeBroadcast(Location location)
    {
       Intent i = new Intent();
       i.setAction(LOCATION_BROADCAST);
       i.putExtra("Location", location);
       sendBroadcast(i);
       Log.v("Tracker Service", "Odeslan broadcast souřadnic.");
    }
   
   private void InitializeAll()
   {
      Latitude = 0;
      Longitude = 0;
      altitude = 0;
      InitializeReciever();
      startLocationService();
      //InitializeLL();
   }
   
    @Override
    public void onCreate(){
       // super.onCreate();
       DbManager = new MyDatabaseManager(this);
       DbManager.open();
       //InitializeReciever();
      // InitializeLL();
       
       Log.v("Service", "Vytvoren service.");
    }
   
    @Override
    public IBinder onBind(Intent arg0) {
       return null;
    }
   
    @Override
    public void onStart(Intent intent, int startid) {
       Log.v(TrackerService.class.getSimpleName(), "Service spusten.");
       InitializeAll();
      // InitializeAll();
     //  updt();
     //  loadSharedPreferences();
      // registerReceiver(MyRecieverService, new IntentFilter("com.vyhlidal.GPStracker.Action.Update"));
     //  registerReceiver(MyRecieverService, new IntentFilter(ExportFile.GET_DATA_FROM_DATABASE));
       super.onStart(intent, startid);
    }
   
    private void stopLocService()
    {
       locMgr.removeUpdates(this);
       stopSelf();
    }
   
    private void startLocationService()
    {

       locMgr = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
       LocationProvider gps = locMgr.getProvider(LocationManager.GPS_PROVIDER);
        locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 7,this);
        
        
    }
   
   
  /*  private void updt()
    {
           //ziskam LM ze ktereho potom budu ziskavat pomoci metod souradnice
           LocationListener locationListener = new LocationListener() {
          @Override
          public void onProviderEnabled(String provider) {
             // TODO Auto-generated method stub               
          }
         
          @Override
          public void onProviderDisabled(String provider) {
             GPSDisabled();
             Log.v("Tracker service", "Hláška o zapnutí gps.");
          }
         
          @Override
          public void onLocationChanged(Location location) {
             if(record){ 
                addRecordToDb(location, recordId);
               //MakeBroadcast(location);}
                Intent i = new Intent();
                  i.setAction(LOCATION_BROADCAST);
               //   i.putExtra("Location", location);
                  sendBroadcast(i);
                  Log.v("Tracker Service", "Odeslan broadcast souřadnic.");}
             Log.v(TrackerService.class.getSimpleName(), "Probehlo odeslani broadcastu souradnic.");
          }

         @Override
         public void onStatusChanged(String arg0, int arg1, Bundle arg2)
         {
            
         }
       };
       
       lmngr.requestLocationUpdates(LocationManager.GPS_PROVIDER,2500,0,locationListener);
     
       
       Log.v(TrackerService.class.getSimpleName(), "Probehla aktualizace souradnic.");
    }*/
   
   /* private void InitializeLL()
    {
       LocationManager locMgr = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
       LocationProvider gps = locMgr.getProvider(LocationManager.GPS_PROVIDER);

         locMgr.requestLocationUpdates(gps.getName(), 3000, 5,
               new LocationListener() {
               public void onLocationChanged(Location location)
               {
                     if(record){ 
                       addRecordToDb(location, recordId);
                      // MakeBroadcast(location);
                       Intent i = new Intent();
                         i.setAction(LOCATION_BROADCAST);
                         i.putExtra("Location", location);
                         sendBroadcast(i);
                         Log.v("Tracker Service", "Odeslan broadcast souřadnic.");
                        }
               }
               public void onStatusChanged(String s, int i, Bundle bundle) {
                  switch(i)
                  {
                  case LocationProvider.AVAILABLE:
                     Log.v("Service", "Gps FUNGUJE");
                  break;
                  case LocationProvider.OUT_OF_SERVICE:
                     Log.v("Service", "Gps mimo provoz");
                     
                     break;
                  case LocationProvider.TEMPORARILY_UNAVAILABLE:
                     Log.v("Service", "Gps Dočasně nejde");
                     InitializeLL();
                     break;
                  }
                  
               }
               public void onProviderEnabled(String s) {
                  // try switching to a different provider
               }
               public void onProviderDisabled(String s) {
                  // try switching to a different provider
               }
             });
       
    }*/
   
    /*-----   ------*/
    public void enableRecord(int updateTime)
   {
       record = true;
      UpdateTime = updateTime;
      recordId++;
   }
   
   public void pauseRecord()
   {
      record = false;
   }
   
   public void resumeRecord(int updateTime)
   {
      UpdateTime = updateTime;
      record = true;
   }
   
   public void disableRecord()
   {
      record = false;
      stopLocService();
   }
   
   public void setUpdateTime(int t)
   {
      UpdateTime = t;
   }
   
   private void removeAllRecords()
   {
      DbManager.clearTable();
   }
   private void IncreaseRId()
   {
      recordId++;
   }
   
   public ArrayList<MyData> getAllRecords()
   {
      return DbManager.getAllRowsAsArrays();
   }
   
   public ArrayList<Object> getRecord(int pos)
   {
      return DbManager.getRowAsArray(pos);
   }
   public ArrayList<MyData> getRecordsById(int id)
   {
      return DbManager.getAllRecordsById(id);
   }
   
   private ArrayList<Integer> getAllRecordsId()
   {
      return DbManager.getAllRecordsId();
   }
   
   private void addRecordToDb(Location location, int rId)
   {
      //1. otestovat zda muzu zaznamenvat
      //2. muzu, spustim db managera a poslu mu zaznamy
      String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
            
      if(record)
      {
         Log.v(TrackerService.class.getSimpleName(), "Pridavam zaznam do databaze.");
         DbManager.addRow(location.getLongitude(), location.getLatitude(), location.getAltitude(), currentDateTimeString, rId);
      }
   }
   
   private void addRecordsFromFileToDb(ArrayList<MyData> newRecords)
   {
      Log.v(TrackerService.class.getSimpleName(), "Pridavam zaznam ze souboru do databaze.");
      IncreaseRId();
      String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
      for(int i = 0; i < newRecords.size(); i++)
      {
         MyData md = newRecords.get(i);
         DbManager.addRow(md.getLong(), md.getLat(), md.getAlt(), currentDateTimeString, recordId);
         
      }
      
   }
   
   private void InitializeReciever(){
      Log.v("Tracker Service", "Vytvarim reciever");
    MyRecieverService = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent)
        {           
           Log.v("Tracker Service", "Prijat broadcast od Trackeru.");
           if(intent.getAction().equals(GPSTracker.UPDATE_SERVICE_BROADCAST))
           {
                 int i = intent.getIntExtra(GPSTracker.START_RECORD, -1);
                 if(i != -1)
                 {
                    enableRecord(i);
                    //Toast.makeText(context, "Zaznam povolen.", Toast.LENGTH_SHORT).show();
                 }
                 
                 int j = intent.getIntExtra(GPSTracker.PAUSE_RECORD, -1);
                 if(j != -1)
                 {
                    pauseRecord();
                    //Toast.makeText(context, "Zaznam pozastaven.", Toast.LENGTH_SHORT).show();
                 }
                 
                 int k = intent.getIntExtra(GPSTracker.STOP_RECORD, -1);
                 if(k != -1)
                 {
                    disableRecord();
                    //Toast.makeText(context, "Zaznam ukončen.", Toast.LENGTH_SHORT).show();
                 }
                 
                 int l = intent.getIntExtra(GPSTracker.CONTINUE_RECORD, -1);
              
                 if(l != -1)
                 {
                    resumeRecord(l);
                    //Toast.makeText(context, "Záznam pokračuje.", Toast.LENGTH_SHORT).show();
                 }
                 int m = intent.getIntExtra(GPSTracker.DROP_DATABASE, -1);
                 if(m != -1)
                 {
                    removeAllRecords();
                    //Toast.makeText(context, "Zaznam povolen.", Toast.LENGTH_SHORT).show();
                 }
           
           }
           else if(intent.getAction().equals(ExportFile.GET_DATA_FROM_DATABASE))
           {
              int i = intent.getIntExtra(ExportFile.GET_DATA, -10);
              if(i != -10)
              {
                 if(i == -1)
                 {
                    //get all records ids from db
                    ArrayList<Integer> tmpRecords = getAllRecordsId();
                    
                    Intent intentAllData = new Intent(DATA_BROADCAST);                    
                    intentAllData.putIntegerArrayListExtra("AllRecordsIdFromDb", tmpRecords );
                    sendBroadcast(intentAllData);
                 }
                 else if(i == -2)
                 {///////////////////////////////////////////////////////////
                    ArrayList<MyData> tmpRecordAll = getAllRecords();
                    Intent intentAllData = new Intent(DATA_BROADCAST);
                    intentAllData.putParcelableArrayListExtra("AllRecords", tmpRecordAll);
                    sendBroadcast(intentAllData);
                 }
                 else
                 {
                    ArrayList<MyData> tmpRecords = getRecordsById(i);
                    Intent intentAllData = new Intent(DATA_BROADCAST);
                    intentAllData.putParcelableArrayListExtra("AllRecordsByID", tmpRecords);
                    sendBroadcast(intentAllData);
                    
                    
                 }
                 
                 }
           }else if(intent.getAction().equals(ExportFile.SEND_DATA_TO_DATABASE))
           {
              ArrayList<MyData> myData = intent.getParcelableArrayListExtra("newData");
              addRecordsFromFileToDb(myData);
           }
        }
        
     }; 
     {
         Log.v("Tracker", "Receiver spusten.");
      }
    RegisterAllRecievers();
     
   }
   
   private void RegisterAllRecievers()
   {
      IntentFilter filter = new IntentFilter();
        filter.addAction("com.vyhlidal.GPStracker.Action.Update");
        IntentFilter filter2 =  new IntentFilter(ExportFile.GET_DATA_FROM_DATABASE);
        IntentFilter filter3 = new IntentFilter(ExportFile.SEND_DATA_TO_DATABASE);
        registerReceiver(MyRecieverService, filter);
        registerReceiver(MyRecieverService, filter2);
        registerReceiver(MyRecieverService, filter3);
   }
     
   private void StopRecievingIntents()
   {
      unregisterReceiver(MyRecieverService);
   }
     private void GPSDisabled()
     {
        Toast.makeText(this, "Gps je vypnutá, prosím zapněte gps.", Toast.LENGTH_SHORT).show();
     }
     @SuppressWarnings("unused")
   private void updateSharedPreference()
     {
        SharedPreferences myPrefs = this.getSharedPreferences(GPSTracker.PREFERENCE_FILENAME, MODE_WORLD_READABLE);
         SharedPreferences.Editor prefsEditor = myPrefs.edit();
         prefsEditor.putBoolean(RECORD, record);
         prefsEditor.putInt(RECORD_ID, recordId);
         prefsEditor.putInt(UPDATE_TIME, UpdateTime);
         prefsEditor.commit();
       
         Log.v("Data zalohovana", "Dokonceno zalohovani dat.");
       
     }
     
     @SuppressWarnings("unused")
   private void loadSharedPreferences()
     {
        SharedPreferences myPrefs = this.getSharedPreferences(GPSTracker.PREFERENCE_FILENAME, MODE_PRIVATE);
        record = myPrefs.getBoolean(RECORD, false);
        recordId = myPrefs.getInt(RECORD_ID, 0);
        UpdateTime = myPrefs.getInt(UPDATE_TIME, 1000);
       
        Log.v("Nahrana data", "Dokonceno nahrati dat ze zalohy");
       
       
     }

   @Override
   public void onLocationChanged(Location location) {
      if(record){ 
          addRecordToDb(location, recordId);
        
           Intent i = new Intent();
            i.setAction(LOCATION_BROADCAST);
            i.putExtra("latitude", location.getLatitude());
            i.putExtra("longitude", location.getLongitude());
            i.putExtra("altitude", location.getAltitude());
            i.putExtra("speed", location.getSpeed());
            i.putExtra("time", location.getTime());
            i.putExtra("bearing", location.getBearing());
            
            sendBroadcast(i);
            Log.v("Tracker Service", "Odeslan broadcast souřadnic.");
           }
      
   }

   @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 i, Bundle arg2) {
      // TODO Auto-generated method stub
      switch(i)
       {
       case LocationProvider.AVAILABLE:
          Log.v("Service", "Gps FUNGUJE");
       break;
       case LocationProvider.OUT_OF_SERVICE:
          Log.v("Service", "Gps mimo provoz");
          
          break;
       case LocationProvider.TEMPORARILY_UNAVAILABLE:
          Log.v("Service", "Gps Dočasně nejde");
          
          break;
       }
      
   }
   
}

If someone wants i can upload whole source code. Thank you for any help.
skodik
Freshman
Freshman
 
Posts: 6
Joined: Thu Feb 10, 2011 9:47 pm

Top

Re: Crash of gps tracking applicaiton

Postby da3dalu5 » Thu Jun 09, 2011 10:44 am

Hi, not sure exactly what you are trying to do in your app but if it will help I just posted up some code that simply returns current location, current speed and average speed.

map-problems-f26/getting-gps-location-calculating-speed-and-showing-on-a-map-t53427.html

I had a good few problems but my main problem was trying to reinvent the wheel and write functionallity that was already implimented. Maybe looking over that code will make something click.

best of luck!
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Re: Crash of gps tracking applicaiton

Postby skodik » Thu Jun 09, 2011 11:46 am

To da3dalu5: Hi, i walt thru your code and in the last version you have 2 location listeners. It is quite redundant, one location listener would work fine. Your app is quite fine, but its not solving my problem :(
My app should do this: I have main activity called Tracker and service which runs in the background. When onLocationChange occures, the service send this location to GUI(main activity Tracker) thru sendBroadcast. Everything is ok, but after 10 gps locations application crashes and I cannot find out why.
skodik
Freshman
Freshman
 
Posts: 6
Joined: Thu Feb 10, 2011 9:47 pm

Re: Crash of gps tracking applicaiton

Postby da3dalu5 » Thu Jun 09, 2011 4:24 pm

skodik wrote:To da3dalu5: Hi, i walt thru your code and in the last version you have 2 location listeners. It is quite redundant, one location listener would work fine.


Are you sure? I have this line to create the listener : "LocationListener locationListener;"
and then this one to actually initiallise it: "locationListener = new LocationListener() {"
which is followed by the "onLocationChanged" method

skodik wrote:Your app is quite fine, but its not solving my problem :(
My app should do this: I have main activity called Tracker and service which runs in the background. When onLocationChange occures, the service send this location to GUI(main activity Tracker) thru sendBroadcast. Everything is ok, but after 10 gps locations application crashes and I cannot find out why.


I have updated the code now to use a service also and the code still runs correctly and endlessly if you want to have a look at the newer code :)

ALSO:
I have done a bit of searching around the internet and found someone having the same problem. There was, however, only one response but I thought it could be useful.

Are you sure it crashes because of this message? The log message is produced by an internal component. Is there anything else in the log? I've seen this message a couple of times but it never crashed any of my activities/services.


So you might want to recheck your log cat in eclipse. I combed through my own log cat to see if i was getting that message (with a working program) to see if I could eliminate that as the problem but unfortunately it didn't appear

and here:http://www.mentby.com/Group/android-developers/16-gps-location-provider-stop-unexpectedly-exceeded-minfixcount-bouncing-back-and-forth.html

someone mentions that this is a common bug in android version 1.6 so if you are coding your app with compatibility for 1.6 this might also be the problem. I initially started coding for 1.6 but was having quite a few problems with the emulator so I created a new 2.1 emulator and project, then copy/pasted all my code into the new project and the problems were gone. So if you are coding for 1.6 i recomment upgrading to 2.1... unless you absolutely have to code for 1.6.
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Re: Crash of gps tracking applicaiton

Postby skodik » Sat Jun 11, 2011 2:33 pm

to da3dalu5:
Hi, i solved my problem :-D Problem was somewhere else :-D Iam quite happy right now. Finaly i can finish my app :)
skodik
Freshman
Freshman
 
Posts: 6
Joined: Thu Feb 10, 2011 9:47 pm

Re: Crash of gps tracking applicaiton

Postby da3dalu5 » Mon Jun 13, 2011 10:52 am

skodik wrote:to da3dalu5:
Hi, i solved my problem :-D Problem was somewhere else :-D Iam quite happy right now. Finaly i can finish my app :)


Ah good! Glad to hear it! What was the problem in the end? as a matter of interest :D
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Top

Re: Crash of gps tracking applicaiton

Postby skodik » Mon Jun 13, 2011 3:07 pm

Problem was at the method for rounding double on 2 decimal values. I just put there my old method and everything works fine :)
skodik
Freshman
Freshman
 
Posts: 6
Joined: Thu Feb 10, 2011 9:47 pm

Top

Return to Map Problems

Who is online

Users browsing this forum: Exabot [Bot] and 3 guests