如何解决应用程序崩溃

时间:2014-04-08 13:05:40

标签: android

正在开发GPS跟踪应用程序。当我按下登录按钮时,它必须显示纬度经度和准确度。它无法正常工作,应用程序崩溃。请帮我解决这个问题。提前谢谢。

这是我的activity.class:

btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AndroidGPSTrackingActivity.this.startService(new Intent(AndroidGPSTrackingActivity.this, GPSTracker.class));
                // create class object
                 // MyTimerTask myTask = new MyTimerTask();
                 Context c = getApplicationContext();
                  SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(c);
                @SuppressWarnings("unused")
                SharedPreferences.Editor editor = app_preferences.edit();
                    TimerTask scanTask;
                    final Handler handler = new Handler();
                    Timer t = new Timer();
                    scanTask = new TimerTask() {
                        GPSTracker gps;
                        List<Double> l = new ArrayList<Double>();
                        TreeMap<Double,List<Double>> list = new  TreeMap<Double,List<Double>>();
                             public void run() {
                                    handler.post(new Runnable() {
                                           // @SuppressLint("UseValueOf")
                                            @SuppressLint("UseValueOf")
                                            public void run() {
                                                  Context c = getApplicationContext();
                                                  SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(c);
                                                SharedPreferences.Editor editor = app_preferences.edit();
                                                int counter = app_preferences.getInt("counter", 0);
                                              Log.i("log", "maaaap"+list);
                                                Double latitude=new Double(0.0d);
                                                Double longitude=new Double(0.0d);
                                                    l = new ArrayList<Double>();
                                                    gps = new GPSTracker(AndroidGPSTrackingActivity.this);
                                                    // check if GPS enabled     
                                                    if(gps.canGetLocation()){

                                                         l.add(gps.getLatitude());
                                                         l.add(gps.getLongitude());
                                                         list.put(gps.getAccur(),l);
                                                         Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + gps.getLatitude() + "\nLong:" + gps.getLongitude()+ "\nAccracy:"+gps.getAccur(), Toast.LENGTH_SHORT).show();

                                                         Log.i("log", "latitude"+gps.getLatitude());
                                                         Log.i("log", "longitude"+gps.getLongitude());
                                                         Log.i("log", "gps.getAccur()"+gps.getAccur());
                                                         Log.d("tag", "Finding Latitude");
                                                         latitude = gps.getLatitude();
                                                        Log.d("tag", "Lat: "+String.valueOf(latitude));
                                                        Log.d("tag", "Finding Longitude");
                                                        longitude  = gps.getLongitude();
                                                        Log.d("tag", "Lon: "+String.valueOf(longitude));
                                                        String Text =
                                                        "\nLat: " + gps.getLatitude() +
                                                        "\nLan:" + gps.getLongitude()+"\nAcrcy="+gps.getAccur();
                                                       //txtData.setText(Text);


                                                        sendSMS(readfromFilesms(), Text);

                                                    }

                                                if(counter<12)
                                                  {
                                                    if(gps.getAccur()<=3.0D)
                                                    {
                                                        Double  d =  (Double)list.firstKey();
                                                        Log.i("log", "gps.firstKey()"+d);
                                                        @SuppressWarnings("rawtypes")
                                                        List l1 = (List)list.get(d);
                                                        Log.i("log", "gps.l1()"+(Double)l1.get(0));
                                                        Log.i("log", "gps.l2"+(Double)l1.get(1));
                                                        latitude = (Double)l1.get(0);
                                                        longitude = (Double)l1.get(1);
                                                       // String[] s = {"manjugowda.manju2@gmail.com"};
                                                        //SendMail(s,latitude.toString(),longitude.toString(),"22");
                                                        editor.putInt("counter", 0);
                                                        editor.commit(); // Very important
                                                        finish();
                                                        //Toast.makeText(getApplicationContext(), "Your Location is - \nLong: "+d , Toast.LENGTH_LONG).show();
                                                    }
                                                    else
                                                    {
                                                        counter = app_preferences.getInt("counter", 0);
                                                        Log.i("log", "counter"+counter);
                                                        editor.putInt("counter", ++counter);
                                                        editor.commit();
                                                        finish();// Very important
                                                    }

                                                  }
                                                else
                                                {
                                                    Double  d =  (Double)list.firstKey();
                                                    Log.i("log", "gps.firstKey()"+d);
                                                    @SuppressWarnings("rawtypes")
                                                    List l1 = (List)list.get(d);
                                                    Log.i("log", "gps.l1()"+(Double)l1.get(0));
                                                    Log.i("log", "gps.l2"+(Double)l1.get(1));
                                                    latitude = (Double)l1.get(0);
                                                    longitude = (Double)l1.get(1);
                                                    //@SuppressWarnings("unused")
                                                    //String[] s = {"manjugowda.manju2@gmail.com"};
                                                   // SendMail(s,latitude.toString(),longitude.toString(),"22");
                                                    editor.putInt("counter", 0);
                                                    editor.commit(); // Very important
                                                    finish();
                                                    //Toast.makeText(getApplicationContext(), "Your Accurecy is - \n: "+d , Toast.LENGTH_LONG).show();
                                                }
                                            }
                                   });
                            }};
                        t.schedule(scanTask,1000,90000000);  
                        finish();
        }
        });

logcat错误:

04-08 18:27:01.438: E/ActivityThread(23915):    at java.lang.reflect.Method.invoke(Method.java:515)
04-08 18:27:01.438: E/ActivityThread(23915):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
04-08 18:27:01.438: E/ActivityThread(23915):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
04-08 18:27:01.438: E/ActivityThread(23915):    at dalvik.system.NativeStart.main(Native Method)
04-08 18:27:01.904: I/log(23915): maaaap{}
04-08 18:27:01.925: D/GPS Enabled(23915): GPS Enabled
04-08 18:27:01.925: I/System.out(23915): inside location manager
04-08 18:27:01.929: D/AndroidRuntime(23915): Shutting down VM
04-08 18:27:01.929: W/dalvikvm(23915): threadid=1: thread exiting with uncaught exception (group=0x416c8d40)
04-08 18:27:01.948: E/AndroidRuntime(23915): FATAL EXCEPTION: main
04-08 18:27:01.948: E/AndroidRuntime(23915): Process: com.example.gpstracking, PID: 23915
04-08 18:27:01.948: E/AndroidRuntime(23915): java.lang.NullPointerException
04-08 18:27:01.948: E/AndroidRuntime(23915):    at com.example.gpstracking.AndroidGPSTrackingActivity$1$1$1.run(AndroidGPSTrackingActivity.java:163)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at android.os.Handler.handleCallback(Handler.java:733)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at android.os.Handler.dispatchMessage(Handler.java:95)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at android.os.Looper.loop(Looper.java:136)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at android.app.ActivityThread.main(ActivityThread.java:5102)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at java.lang.reflect.Method.invokeNative(Native Method)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at java.lang.reflect.Method.invoke(Method.java:515)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
04-08 18:27:01.948: E/AndroidRuntime(23915):    at dalvik.system.NativeStart.main(Native Method)
04-08 18:27:03.605: I/Process(23915): Sending signal. PID: 23915 SIG: 9

GPSTracker.class:

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    Double accur;

    public Double getAccur() {
        return accur;
    }

    public void setAccur(Double accur) {
        this.accur = accur;
    }

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 12; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 0; // 1 sec

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public Object getAccuracy;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            /*isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            /*if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                /*this.canGetLocation = true;
                if(isNetworkEnabled){
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network","Network");
                    if(locationManager!=null){
                        location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if(location!=null){
                            System.out.println("inside location");
                            latitude = location.getLatitude();

                            System.out.println("lat"+latitude);
                            longitude = location.getLongitude();
                        }
                    }
                }*/
                if (isGPSEnabled) {
                    if (location == null) {

                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled","GPS Enabled");

                        if (locationManager != null) {

                            System.out.println("inside location manager");
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {

                                System.out.println("inside location");
                                latitude = location.getLatitude();

                                System.out.println("lat"+latitude);
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }

            if(location!=null)
            {
                setAccur(new Double(location.getAccuracy()));
            }

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

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    /*public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }*/

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
       /* alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });*/

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

1 个答案:

答案 0 :(得分:1)

根据您的代码。我找到了崩溃的问题。可能是你的gps的实例是null或者被改为null。先检查一下

if(gps!=null){
  //your code
}else{
   Log.i("Your Classs Name::","GPS Object is null")
}

我确定你会收到日志消息,因为GPS对象为空..

如果仍然获得Null,则重新初始化gps对象。

相关问题