javaandroidtry-catchcatch-block

How to refactor this If/else statement in a try/catch block?


I was wondering if there is a better way to code this piece of code:

private void getLatitudeAndLongitudeFromZipcode() {
        String zipcode = mSharedPreferences.getString("Zipcode", "");

        try {
            List<Address> address = geocoder.getFromLocationName(zipcode, 1);
            if ((address != null ? address.size() : 0) > 0) {
                Address first = address.get(0);
                mLatitude = first.getLatitude();
                mLongitude = first.getLongitude();
                mCurrentLocationName = getLocationAsName();
                mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
                        .apply();
                mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
                        .apply();
            } else {
                getOldZipcodeLocation();//duplicate method call
            }
        } catch (IOException e) {
            getOldZipcodeLocation();//duplicate method call
            e.printStackTrace();
        }
    } 

Basic idea is that if they don't have internet and an exception is thrown, I want to get the old coordinates from storage. However, I also want to get the old coordinates if they are currently in a place that doesn't give them coordinates. For example, if the geocoder returns null. What bothers me is the duplicate method call in the else block and catch block. Any way to make this code cleaner? I'll take any other tips as well!


Solution

  • Yes you can , 1st get address through IOException separately , then use address in your if..else statement . that's it .

     private void getLatitudeAndLongitudeFromZipcode() {
    
        String zipcode = mSharedPreferences.getString("Zipcode", "");
        List<Address> address = null;
        try {
            address = new Geocoder(this).getFromLocationName(zipcode, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        if ((address != null ? address.size() : 0) > 0) {
            Address first = address.get(0);
            mLatitude = first.getLatitude();
            mLongitude = first.getLongitude();
            mCurrentLocationName = getLocationAsName();
            mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
                    .apply();
            mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
                    .apply();
        } else {
            getOldZipcodeLocation();
    
        }
    }