dinsdag 20 augustus 2013

Forecast weather API android lib

I used to call the google weather API within several Android apps. Until Google once decided to shut that service down. Since then I have been looking around for an alternative.

I finally found a great service hosted by forecast. They have a visually attractive presentation on their homepage. But what's more important is that their pricing model is also nice. You get 1000 free API calls a day. If you want more you get to pay.

Anyway, I decided to subscribe for that service. In return you get an API key. Next I created a simple library project to parse the result.

What it does is a background http get (using the default httpClient) with the parameters you provided with the builder. The json response is then parsed using gson. A quick example:

    double latitude = 37.8267;
    double longitude = -122.423;

    ForecastCallBuilder builder = ForecastCallBuilder.getInstance();
    builder.key("YOUR_API_KEY_HERE").latitude(latitude)
            .longitude(longitude).units(Units.AUTO);
    ResponseListener listener = new ResponseListener() {

        @Override
        public void handleResponse(HttpServiceOutput result) {
            if( result == null || result.getException() != null ){
                Toast.makeText(getApplicationContext(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }
            else {
                // you should check for nullpointers on the forecast data before display
                Toast.makeText(getApplicationContext(), "Summary: " + result.getForecastResponse().getCurrently()
                            .getSummary(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void preExecution() {
            Toast.makeText(getApplicationContext(), "Fetching forecast data now...", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void postExecution() {
            // here you cold inform about call being done
        }

    };
    builder.performCall(listener);

For more information visit the project at https://github.com/hanscappelle/android-forecast-lib.
Forecast developer documentation is available at https://developer.forecast.io/docs/v2.

Geen opmerkingen:

Een reactie plaatsen