ReverseGeocodingTask task to a method

ぃ、小莉子 提交于 2019-12-25 07:28:28

问题


I grab a code from the android site that do the reverse geocoding (transfering a location from numbers to a text)

It's working fine but since my application has changed a bit I need to change this code into a normal method, right now it's an AsyncTask. It should get a Location and return a string.

This code is a bit strange to me so I need your help guys:

private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> 
{
    Context mContext;

    public ReverseGeocodingTask(Context context) 
    {
        super();
        mContext = context;
    }

    @Override
    protected Void doInBackground(Location... params) 
    {
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

        Location loc = params[0];
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        } catch (IOException e) {
            e.printStackTrace();
            // Update address field with the exception.
            LocationService.this.address = e.toString();
        }
        if (addresses != null && addresses.size() > 0) 
        {
            Address address = addresses.get(0);
            // Format the first line of address (if available), city, and country name.
            String addressText = String.format("%s, %s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                    address.getLocality(),
                    address.getCountryName());
            // Update address field on UI.
           // Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
            LocationService.this.address = addressText;
        }
        return null;
    }
}

回答1:


You start by making a method like so

public String reverseGeocode(Location loc) {


}

change the line that grabs the first location, being the only one used, and remove it - you already have loc

//Location loc = params[0];

Then instead of setting the address to that location service, just return it:

//LocationService.this.address = addressText;
return addressText;

Splice those into the method, remove the unnecessary return statement at the end, and you're golden.

Upon a closer look I'm also seeing an exception you'll simply want to throw up the chain instead of handling inside this method. Let that get handled by whatever calls your method on a case-by-case basis: it's not a problem this method can solve.



来源:https://stackoverflow.com/questions/14489714/reversegeocodingtask-task-to-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!