显示来自世界天气在线api的数据

时间:2014-07-23 07:22:22

标签: android

我正在使用世界天气在线API开发天气应用程序  对于android.How我在应用程序中显示数据?数据显示在logcat中。以下是我的代码。

MainActivity.java

公共类MainActivity扩展了ListActivity {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";

// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dataList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                data = jsonObj.getJSONArray(TAG_DATA);

                // looping through All Contacts
                for (int i = 0; i < data.length(); i++) {
                    JSONObject c = data.getJSONObject(i);



                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value


                    // adding contact to contact list
                    dataList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(MainActivity.this,
                dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
                        R.id.name });

        setListAdapter(adapter);
    }

}

}

ServiceHandler.java

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

}

1 个答案:

答案 0 :(得分:0)

首先,这种格式将参考V1免费版本。世界天气在线已发布v2,这是优越的。我正在更新,看到这个问题坐在那里,所以我会根据我的工作做出回答。

您正在使用AsyncTask,这是我对AsyncTask的调用。你应该知道我使用我的“DataPoint”类来简单地包含我需要使用的WWO数据。根据您的问题,您可以在屏幕上看到我将放在DataPoint对象中的数据,因为在queryWeatherService()的末尾,您将得到一组已解析的数据。

//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{       
        // This method will retrieve the data from the weather service
        DataPoint newDataPoint = new DataPoint();
        if (!waiting)
            {
            try{
                newDataPoint = new WeatherServiceClass().execute(
                String.valueOf(getlatitude()),  //Not shown here: pass in some String of a float value of of your lat coordinate.
                String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
                                .get();
                    } catch (InterruptedException | ExecutionException e)
                    {
                        e.printStackTrace();
                    }
            }
        return newDataPoint;
        // Documentation:
        // https://developer.worldweatheronline.com/page/documentation
    }

扩展AsyncTask的WeatherServiceClass

public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
    private String latitude;
    private String longitude;

    public WeatherServiceClass() {
    }

    @Override
    protected DataPoint doInBackground(String... params) {
        DataPoint dp = new DataPoint();
        JSONWeatherParser jparser = new JSONWeatherParser();
        latitude = params[0];
        longitude = params[1];
        String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
        try {
            dp = jparser.getWeather(data);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return dp;
        //Reference:
        // http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
    } 
}

这是WeatherHttpClient类:

public class WeatherHttpClient {

    private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
    private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";

    public String getWeatherData(String latitude, String longitude){
        HttpURLConnection con = null;
        InputStream is=null;

        try{
            con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.connect();

            //Reading the response
            StringBuffer buffer = new StringBuffer();
            is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while ((line=br.readLine()) != null)
                buffer.append(line + "\r\n");
            is.close();
            con.disconnect();
            return buffer.toString();
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
        finally {
            try { is.close();} catch(Throwable t){}
            try { con.disconnect();} catch(Throwable t){}
        }

        return null;
    }

最后,这是我的JSONWeatherParser:

public class JSONWeatherParser {

    public JSONWeatherParser() {

    }

    public DataPoint getWeather(String data) throws JSONException {
        DataPoint dp = new DataPoint();
        Weather weather = new Weather();   //This is just a class that has a bunch of strings in it for the weather info.
        JSONObject jObj = new JSONObject(data);

        //Parsing JSON data
        JSONObject dObj = jObj.getJSONObject("data");
        JSONArray cArr = dObj.getJSONArray("current_condition");
        JSONObject JSONCurrent = cArr.getJSONObject(0);
        weather.setCurrent_temp(getString("temp_F",JSONCurrent));
        weather.setHour(getString("observation_time",JSONCurrent));
        JSONArray jArr = dObj.getJSONArray("weather");
        JSONObject JSONWeather = jArr.getJSONObject(0);
        JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
        JSONObject JSONIcon = jArrIcon.getJSONObject(0);
        weather.setDate(getString("date",JSONWeather));
        weather.setPrecipmm(getString("precipMM",JSONWeather));
        weather.setTempMaxc(getString("tempMaxC",JSONWeather));
        weather.setTempMaxf(getString("tempMaxF",JSONWeather));
        weather.setTempMinf(getString("tempMinF",JSONWeather));
        weather.setTempMinc(getString("tempMinC",JSONWeather));
        weather.setWeatherCode(getString("weatherCode",JSONWeather));
        weather.setWeatherIconURL(getString("value",JSONIcon));
        weather.setWinddir16point(getString("winddir16Point",JSONWeather));
        weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
        weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
        weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
        dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
        // For details of these operations and how each works go here:
        // http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
        return dp;
    }

    private static String getString(String tagName, JSONObject jObj)
            throws JSONException {
        return jObj.getString(tagName);
    }
}