Android:java运行时异常无法创建服务

时间:2013-04-10 17:58:56

标签: android

我创建了一个项目,该项目使用一个名为service class的类来连续获取位置并将其保存到数组列表中。但它显示出一些错误。该项目是在Android 2.1

Serviceclass.java

package com.example.tracemeendpointsjson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import Trace.date.TimeDate;
import android.app.Service;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class ServiceClass  extends Service implements LocationListener {
    double mLongitude ;
    double mLatitude;
    boolean check;
    public static int k;
    CommonClass cmn;
    MainActivity ma;
    int i;
    LocationManager mLocationManager;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(ServiceClass.this, "Service started", Toast.LENGTH_SHORT).show();
        cmn=new CommonClass();
        ma=new MainActivity();

        cmn.StartTime=new TimeDate().timeToString();
         System.out.println("StartTime ::  "+cmn.StartTime);
         cmn.StartDate=new TimeDate().dateToString();
         System.out.println("StartDate ::  "+cmn.StartDate);



        check = true;
        i = 0;
        k=0;
        initializeLocationAndStartGpsThread();


    }


    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        setCurrentGpsLocation(location);    
    }
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

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

    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }





    private void setCurrentGpsLocation(Location location) {
        String bestProvider = "";
        if (location == null) {

            mLocationManager =(LocationManager) getSystemService(LOCATION_SERVICE);
                    mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 1000, 0, this); // Every 10000 msecs  
                    System.out.println("GPS_PROVIDER:  ");
            location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);             

        }
        try {
            mLongitude = location.getLongitude();
         mLatitude = location.getLatitude();

         String la=Double.toString(mLatitude);
         String ln=Double.toString(mLongitude);

         System.out.println("B  4 Size  ::  "+cmn.Lat.size());
         System.out.println("B  4 array  ::  "+cmn.Lat);
         cmn.Lat.add(la);
         cmn.Long.add(ln);
         System.out.println("after size  ::  "+cmn.Lat.size());
         System.out.println("after array  ::  "+cmn.Lat);


         String UpdatedTime=new TimeDate().timeToString();
         cmn.TimeArray.add(UpdatedTime);
         System.out.println("UpdatedTime  ::  "+UpdatedTime);
         System.out.println("cmn.TimeArray  ::  "+cmn.TimeArray.size());
         System.out.println("cmn.TimeArray  ::  "+cmn.TimeArray);

         String UpdatedDate=new TimeDate().dateToString();
         cmn.DateArray.add(UpdatedDate);
         System.out.println("UpdatedDate  ::  "+UpdatedDate);
         System.out.println("cmn.DateArray  ::  "+cmn.DateArray.size());
         System.out.println("cmn.DateArray  ::  "+cmn.DateArray);


         k++;

//          Log.i("hai01", "<long,lat> = <" + mLongitude + "," + mLatitude);
//          System.out.println("LOgGgggggggggggg");
            Message msg = Message.obtain();
            msg.what = 1;
            ServiceClass.this.updateHandler.sendMessage(msg);

            String cityName = null;  
            Geocoder gcd = new Geocoder(ServiceClass.this, Locale.ENGLISH);  

            List<Address> addresses=null;  
            try {  
             addresses = gcd.getFromLocation(mLongitude, mLatitude, 1);  

             if (addresses.size() > 0)  

              System.out.println(addresses.get(0).getLocality());  
             cityName = addresses.get(0).getLocality();  
            } catch (IOException e) {  
             e.printStackTrace();  
            }  



            String s = ln + "\n" + la  
              + "\n\nMy Current City is: " + cityName;  
            Toast.makeText(ServiceClass.this, "City is:"+s, Toast.LENGTH_SHORT).show();

        } catch (NullPointerException e) {
            Log.i("hai02", "Null pointer exception ");
        }
     }



    Handler updateHandler = new Handler() {
        /** Gets called on every message that is received */
        // @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1: {
                Log.i("hai03", "Updated location = " + mLatitude + " " + mLongitude);
                break;
            }
            case 0: {
                Log.i("hai000000000000", "Running");
                break;
            }
                }
            super.handleMessage(msg);
        }
     };








     private void initializeLocationAndStartGpsThread() {
            mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            List<String> providers = mLocationManager.getProviders(true);
            Log.i("hai04", "Enabled providers = " + providers.toString());
            String provider = mLocationManager.getBestProvider(new Criteria(),true);
            Log.i("hai05", "Best provider = " + provider);

            //setCurrentGpsLocation(null);   

         }




     @Override
        public void onDestroy() {
            super.onDestroy();
            check = false;
            i = 0;


           cmn.Lat.clear();
           cmn.Long.clear();
           cmn.FinalDistance.clear();
           ma.finaldist=0.0f;
           cmn.TimeArray.clear();
           cmn.DateArray.clear();


           System.out.println("Clear size  ::  "+cmn.Lat);
           System.out.println("Clear size  ::  "+cmn.Long);
           System.out.println("Clear size  ::  "+cmn.Lat.size());
           System.out.println("Clear size  ::  "+cmn.Long.size());
            Toast.makeText(ServiceClass.this, "Service stopped", Toast.LENGTH_SHORT)
                    .show();
        }

}

Logcat输出是:

04-10 22:55:50.318: E/AndroidRuntime(249): Uncaught handler: thread main exiting due to uncaught exception
04-10 22:55:50.361: E/AndroidRuntime(249): java.lang.RuntimeException: Unable to create service com.example.tracemeendpointsjson.ServiceClass: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2790)
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.app.ActivityThread.access$3200(ActivityThread.java:119)
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1917)
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.os.Looper.loop(Looper.java:123)
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.app.ActivityThread.main(ActivityThread.java:4363)
04-10 22:55:50.361: E/AndroidRuntime(249):  at java.lang.reflect.Method.invokeNative(Native Method)
04-10 22:55:50.361: E/AndroidRuntime(249):  at java.lang.reflect.Method.invoke(Method.java:521)
04-10 22:55:50.361: E/AndroidRuntime(249):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-10 22:55:50.361: E/AndroidRuntime(249):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-10 22:55:50.361: E/AndroidRuntime(249):  at dalvik.system.NativeStart.main(Native Method)
04-10 22:55:50.361: E/AndroidRuntime(249): Caused by: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
04-10 22:55:50.361: E/AndroidRuntime(249):  at java.util.ArrayList.get(ArrayList.java:341)
04-10 22:55:50.361: E/AndroidRuntime(249):  at com.example.tracemeendpointsjson.ServiceClass.setCurrentGpsLocation(ServiceClass.java:143)
04-10 22:55:50.361: E/AndroidRuntime(249):  at com.example.tracemeendpointsjson.ServiceClass.initializeLocationAndStartGpsThread(ServiceClass.java:193)
04-10 22:55:50.361: E/AndroidRuntime(249):  at com.example.tracemeendpointsjson.ServiceClass.onCreate(ServiceClass.java:55)
04-10 22:55:50.361: E/AndroidRuntime(249):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2780)

请帮帮我

1 个答案:

答案 0 :(得分:0)

这是你的罪魁祸首:

04-10 22:55:50.361: E/AndroidRuntime(249): Caused by: java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
04-10 22:55:50.361: E/AndroidRuntime(249):  at com.example.tracemeendpointsjson.ServiceClass.setCurrentGpsLocation(ServiceClass.java:143)

在ServiceClass.java第143行中,您将超出数组的范围,因此导致应用程序崩溃的异常。这就是因为你养成了不把条件块放在括号中的坏习惯,所以你有

if (addresses.size() > 0)  
System.out.println(addresses.get(0).getLocality());  
cityName = addresses.get(0).getLocality();  

你应该

if (addresses.size() > 0)  {
    System.out.println(addresses.get(0).getLocality());  
    cityName = addresses.get(0).getLocality();  
}