简体   繁体   中英

IndexOutOfBoundsException in GeoCoder

In my project I am trying to post my current location to server by using LocationManager . For that I have got an Latitude and Longitude values by using OnLocationChanged method in Location Manager. Also in Button Click event I tried to convert a lat & long values to Address by using Geocoder features. But it crashes my application.

Button Click Code :

            public void onClick(View v) {
                btnflag++;
                if(btnflag==1)
                {

                 String providergps = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                 if(providergps.contains("gps"))
                 {
                        //Check If Internet present
                      // isNetworkAvailable(h, 2000);


                        CheckConnectivity check = new CheckConnectivity();

                        Boolean conn = check.checkNow(getApplicationContext());
                        Boolean conn1=AsyncClass.result;
                         if(conn==true && conn1==true){

                            Criteria criteria = new Criteria();
                            provider = locationManager.getBestProvider(criteria, false);
                            location = locationManager.getLastKnownLocation(provider);
                            locationManager.requestLocationUpdates(provider,0,0,Disclaimer.this);

                            Toast.makeText(getApplicationContext(), latlan, Toast.LENGTH_LONG).show();      
                         Global.setlatlan(latlan);
                         currentdetail();

                        //Hit the Server fot getting Device Information  
                         SettingsService set = new SettingsService();
                            SettingsService.loadingProgress = GUIStaticMethod
                                    .returnProgressBar(Disclaimer.this);

                            GUIStaticMethod.mProgressDialog.setOnDismissListener(new OnDismissListener() {

                                public void onDismiss(DialogInterface dialog) {


                                    // TODO Auto-generated method stub
                                    String Settingres = Global.getResult();

                                    //Toast.makeText(getApplicationContext(), Settingres, Toast.LENGTH_LONG).show();
                                    List<Details> contacts = db.getAllContacts();

                            //check for setting result(Device Information) If Null
                            if(Settingres.equalsIgnoreCase("Web Service Invalid"))
                            {
                                btnflag=0;
                                showAlertDialog1(Disclaimer.this, "Error",
                                        "Your Server Request is Not Responding.Try Again...", false);
                            }
                            else if(Settingres.equals(null)==true)
                            {
                                Toast.makeText(getApplicationContext(), "check DB", Toast.LENGTH_LONG).show();

                                boolean val =contacts.isEmpty();

                                if((contacts.isEmpty())==true)
                                {
                                    Toast.makeText(getApplicationContext(),"Your Application Settings Not Loaded", Toast.LENGTH_LONG).show();
                                }
                                else
                                {
                                    for (Details cn : contacts) {

                                            String log = "APP ID: "+cn.getAPPID()+" ,Unique ID: " + cn.getUniqueID() + " ,Driver Name: " + cn.getDriverName()+ " ,Vehicle Name: " + cn.getVehicleName()+ " ,Mobile number: " + cn.getPhoneNumber()+ " ,Subscrition number: " + cn.getSubscription()+ " ,Email: " + cn.getEmail_id()+ " ,Perm_Location: " + cn.getPermLocation();
                                            Log.d("Name: ", log);
                                            Toast.makeText(getApplicationContext(), log,Toast.LENGTH_LONG).show();
                                            }
                                }
                            }
                            // If Device Informtion Not Avail In Server Store Device Information to Server
                            else if(Settingres.equals("Device Not Updated")==true)
                            {

                                //Insert Device Info To Server by Calling SettingsDB Activity
                                SettingsService1.status="INSERT";
                                SettingDB.flag=0;
                                SettingDB.notflag=1;
                                btnflag=0;
                                Intent setting = new Intent(Disclaimer.this,SettingDB.class);
                                startActivity(setting);


                            }
                            //If Device Information is Available
                            else
                            {
                                //Store ii to Local Setting DB If newly present
                                if((contacts.isEmpty())==true)
                                {
                                    db.addDetails(new Details(Settingres));

                                }
                                //Store ii to Local Setting DB If Already Exist(Drop Existing Table)
                                else
                                {
                                    db.dropAllTable(getApplicationContext());
                                    db.addDetails(new Details(Settingres));

                                }

                                /*Get the Device Information from local Database 
                                for storing Device status to server like AppOpen,Find,Route Accept,
                                Route complete,Route Time Interval*/
                                List<Details> contacts1 = db.getAllContacts();
                                for (Details cn : contacts1) {

                                    String log = "APP ID: "+cn.getAPPID()+" ,Unique ID: " + cn.getUniqueID() + " ,Driver Name: " + cn.getDriverName()+ " ,Vehicle Name: " + cn.getVehicleName()+ " ,Mobile number: " + cn.getPhoneNumber()+ " ,Subscrition number: " + cn.getSubscription()+ " ,Email: " + cn.getEmail_id()+ " ,Perm_Location: " + cn.getPermLocation();
                                    Log.d("Name: ", log);
                                    // Store App ID Globally
                                    Global.setAppID(cn.getAPPID());

                                }

                                new CheckExpires().execute(Global.Appid);
                                CheckExpires.loadingProgress = GUIStaticMethod.returnProgressBar(Disclaimer.this);

                                GUIStaticMethod.mProgressDialog.setOnDismissListener(new OnDismissListener() {  

                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        // TODO Auto-generated method stub
                                        String res = Global.getResult();

                                        if(res.equalsIgnoreCase("Web Service Invalid"))
                                        {
                                            btnflag=0;
                                            showAlertDialog1(Disclaimer.this, "Error",
                                                    "Your Server Request is Not Responding.Try Again...", false);
                                        }
                                         //String val1[]= res.split("string=");
                                        if(res.equalsIgnoreCase("Valid"))
                                        {
                                            //Getting Time Info at which time App Open
                                            CurrentTime tim = new CurrentTime();

                                            /*Store the Device status as App Open on to server By Calling
                                             * PostCurrentLocation Server*/

                                            LocationService curadrloc = new LocationService("App Open");

                                            //It stops location Manager 
                                            //Calling Main Screen Activity
                                            GeneratNotification();
                                            btnflag=0;
                                            Intent mainscr = new Intent(Disclaimer.this, MainScreen.class);
                                            startActivity(mainscr);


                                            SharedPreferences AutoAns = getSharedPreferences(PREFS_NAMES, 0);
                                            SharedPreferences.Editor answer = AutoAns.edit();
                                            answer.putString("AutoAnswer","TRUE");
                                            answer.commit();

                                            finish();
                                        }
                                        else if(res.equalsIgnoreCase("Expired"))
                                        {


                                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(Disclaimer.this);

                                            // Setting Dialog Title
                                            alertDialog.setTitle("Alert Dialog");

                                            // Setting Dialog Message
                                            alertDialog.setMessage("If You Want to Continue Enter Coupon Code...");



                                            // Setting Positive "Yes" Button
                                            alertDialog.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog,int which) {

                                                // Write your code here to invoke YES event
                                                    btnflag=0;
                                                dialog.cancel();
                                                }
                                            });

                                            // Setting Negative "NO" Button
                                            alertDialog.setNegativeButton("COUPON CODE", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                // Write your code here to invoke NO event
                                                    CheckConnectivity check = new CheckConnectivity();
                                                     Boolean conn = check.checkNow(Disclaimer.this);
                                                     //Boolean nwstatus = check.isNetworkAvailable(Disclaimer.this);
                                                     //Boolean conn1=isConnected();
                                                     if(conn == true){
                                                     final EditText input = new EditText(Disclaimer.this);
                                                    input.setSingleLine(true);
                                                    input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
                                                    input.setHint("");
                                                    Pattern pattern = Pattern.compile(".+[0-9]+");
                                                    Matcher appmat = pattern.matcher(input.getText().toString());
                                                    boolean appmatch = appmat.matches();

                                                    AlertDialog.Builder share = new AlertDialog.Builder(Disclaimer.this);
                                                    share.setView(input);
                                                    share.setTitle("Enter Coupon Code");
                                                    share.setPositiveButton("Confirm"
                                                        ,
                                                        new DialogInterface.OnClickListener() {


                                                        public void onClick(DialogInterface dialog, int whichButton) {


                                                            CheckConnectivity check = new CheckConnectivity();
                                                            //Boolean conn1=isConnected(); 
                                                            Boolean conn = check.checkNow(Disclaimer.this);
                                                             if(conn == true){

                                                                if(input.getText().toString().length() == 0)
                                                                {
                                                                    btnflag=0;
                                                                    showAlertDialog1(Disclaimer.this, "Invalid Entry",
                                                                            "This Field can not be Blank.Try Again!!!", false);
                                                                }
                                                                else if(input.getText().toString().length()!= 8)
                                                                {
                                                                    btnflag=0;
                                                                    showAlertDialog1(Disclaimer.this, "Invalid Entry",
                                                                            "This Field must have 8 digits.Try Again!!!", false);
                                                                }
                                                                else if(input.getText().toString().length() > 0 && input.getText().toString().length()==8)
                                                                {



                                                                     //** Web Service Information to enter Coupen Code into Table for Extending Validation 

                                                                    String temp = input.getText().toString();

                                                                    new CoupenMethod().execute(temp);

                                                                    CoupenMethod.loadingProgress = GUIStaticMethod
                                                                                .returnProgressBar(Disclaimer.this);
                                                                              GUIStaticMethod.mProgressDialog.setOnDismissListener(new OnDismissListener() {

                                                                            public void onDismiss(DialogInterface dialog) {

                                                                                String result = Global.getResult();
                                                                                if(result.equalsIgnoreCase("Web Service Invalid"))
                                                                                {
                                                                                    btnflag=0;
                                                                                    showAlertDialog1(Disclaimer.this, "Error",
                                                                                            "Your Server Request is Not Responding.Try again.", false);
                                                                                }
                                                                                else if(result.equals("Invalid"))
                                                                                {
                                                                                    btnflag=0;
                                                                                    showAlertDialog1(Disclaimer.this, "Error",
                                                                                            "Entered Coupen Code is Invalid.", false);
                                                                                }
                                                                                else if(result.equals(null))
                                                                                {
                                                                                    btnflag=0;
                                                                                    showAlertDialog1(Disclaimer.this, "Error",
                                                                                            "Entered Coupen Code is Invalid.", false);

                                                                                }
                                                                                else
                                                                                {
                                                                                    String res[]=result.split("-");
                                                                                    String webres=res[1];
                                                                                    btnflag=0;
                                                                                    showAlertDialog1(Disclaimer.this, "Congratulations",
                                                                                            "Your Activation "+webres, false);
                                                                                }

                                                                        }
                                                                        });



                                                                }   


                                                             }
                                                             else
                                                             {
                                                                 btnflag=0;
                                                                 showAlertDialog1(Disclaimer.this, "No Internet Connection",
                                                                            "You don't have internet connection.", false);

                                                             }
                                                                    }
                                                                }); 
                                                            share.setNegativeButton("Cancel",null);
                                                        share.show();
                                                     }
                                                     else
                                                     {
                                                         btnflag=0;
                                                         showAlertDialog(Disclaimer.this, "No Internet Connection",
                                                                    "You don't have internet connection.", false);
                                                     }


                                                }
                                            });

                                            // Showing Alert Message
                                            alertDialog.show();





                                        }
                                        else if(res.equalsIgnoreCase(null))
                                        {
                                            showAlertDialog1(Disclaimer.this, "Error",
                                                    "Your Request is Invalid.Try Again...", false);
                                        }
                                        btnflag=0;

                                    }
                                });



                            }

                    }       

                    }); 

                         }

                     //If Internet is not Present shows Alert    
                     else{
                         btnflag=0;
                         showAlertDialog(Disclaimer.this, "No Internet Connection",
                                    "You don't have internet connection.", false);

                     }

                 }
                 else
                 {


                        AlertDialog.Builder call1 = new Builder(Disclaimer.this);
                        call1.setTitle("GPS is settings");
                        call1.setMessage("GPS is not enabled. Do you want to go to settings menu?");
                        call1.setCancelable(false);


                                        call1.setPositiveButton(    
                                "Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        btnflag=0;
                                        dialog.cancel();
                                    }
                                });

                                call1.setNegativeButton(
                                                "Settings",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(
                                                            DialogInterface dialog,
                                                            int which) {


                                                        btnflag=0;
                                                        // Application goes to Home Screen
                                                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                                        startActivity(intent);                          

                                                    }
                                                });             


                        call1.show();





                 }
            }

            }

            //Alert Dialog Information for Internet purpose
            public void showAlertDialog(Context context, String title, String message, Boolean status) {
                AlertDialog alertDialog = new AlertDialog.Builder(context).create();

                // Setting Dialog Title
                alertDialog.setTitle(title);

                // Setting Dialog Message
                alertDialog.setMessage(message);

                // Setting alert dialog icon
                //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

                // Setting OK Button
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setClassName("com.android.phone", "com.android.phone.Settings");
                        startActivity(intent);
                    }
                });

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

        });



CurrentDetail Method : 



public void currentdetail()
    {
        Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
        try {
            List<Address> address = geocoder.getFromLocation(lat,lang, 1);

            if(address != null) {
                Address returnedAddress = address.get(0);

                StringBuilder strReturnedAddress = new StringBuilder();

                for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                }
                String curadr = strReturnedAddress.toString();
                Global.setCurrAddress(curadr);
                }
            else{
                Global.setCurrAddress("No Address Defined");
                }
            } 
        catch (IOException e)
            {
            Global.setCurrAddress("No Address Defined");
            e.printStackTrace();
            }
    }

But it shows the Error as follows when i click a button

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.slet.routemytrips.beta.Disclaimer.currentdetail(Disclaimer.java:803)
at com.slet.routemytrips.beta.Disclaimer$2.onClick(Disclaimer.java:204)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14109)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

Note:

  1. It comes specifically for some kind of devices like Galaxy S4, Galaxy Note 2

  2. Also when I check lat and long values it shows the values like (13.1270,803.2701)

The exception is happening because the returned list is empty. You should check that address.size() > 0 as well as address != null .

List<Address> address = geocoder.getFromLocation(lat,lang, 1);
if(address != null) {
    Address returnedAddress = address.get(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM