package eur.one00kb.minipogodynka.weather; import android.content.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import eur.one00kb.minipogodynka.R; // TODO: For all data providers: check if the data parsed is correct and inline with the JSON. // The exception handling part stinks. public abstract class WeatherDataProvider { private final String mUserAgent; /** * Must contain two floating point format specifiers for latitude and longitude, in order */ private String mAPILinkFormat; public WeatherDataProvider(Context context) { mUserAgent = String.format("%s", context.getString(R.string.app_name)); } public void setAPILinkFormat(String format) { mAPILinkFormat = format; } public Map> provide(double latitude, double longitude) throws IOException { String data = fetchData(latitude, longitude); return parseData(data); } /** * @param data The JSON or otherwise data to parse. * @return A sorted hashmap with keys being Dates with just the day, month, and year, and the * values being lists of hourly weather data. */ public abstract Map> parseData(String data); public String fetchData(double latitude, double longitude) throws IOException { URLConnection conn = new URL(String.format(Locale.US, mAPILinkFormat, latitude, longitude)) .openConnection(); conn.setRequestProperty("User-Agent", mUserAgent); StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } reader.close(); return builder.toString(); } }