简体   繁体   English

如何在json中检索天气数据[android]

[英]How to retrieve weather data in json [android]

I want to retrieve weather data from an API as JSON, but it isn't working. 我想以JSON格式从API检索天气数据,但无法正常工作。 How do I pull in weather data, such as a 5-day forecast, into a text view? 如何将天气数据(例如5天天气预报)提取到文本视图中?

My code is below, but I need to somehow adapt it to pass in the JSON 5-day weather forecast and put that into a text view. 我的代码在下面,但我需要以某种方式对其进行调整,以传递JSON 5天天气预报并将其放入文本视图中。

package mytweets.mytweets;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MytweetsActivity extends Activity {

    // we are reading weathe

    final String URL `enter code here`="http://api.openweathermap.org/data/2.5/forecast/daily?q,gb&mode=json&units=metric&cnt=5&APPID=xxxxxxxxxxxxxxxx";

    final String Consumer_Key = "mPfkAwVuuiVYeuZWdHAMzQ";  // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new
    final String Consumer_Secret = "bkmiQqellGg9jnJFj41E8zukYSNk0FX1W7v1nU376rE"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new

    JSONArray tweets = null; //an array of tweets


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mytweets);

        Button btn_token = (Button)findViewById(R.id.get_token);
        btn_token.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new GetTokenTask().execute();
            }
            });

        Button btn_feed = (Button)findViewById(R.id.get_tweets);
        btn_feed.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView txt_token = (TextView)findViewById(R.id.txt_token);
                String token = txt_token.getText().toString();
                new GetTweetsTask().execute(token, URL);
            }
            });
    }

    protected class GetTokenTask extends AsyncTask<Void, Void, String> {  // the class extends AsynTask in order to run as a thread in the background

        @Override
        protected String d    
            try {
                    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                    HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token");  //asks for a token

                    String apiString = Consumer_Key + ":" + Consumer_Secret;
                    String authorization = "Basic " + Base64.encodeToString(apiString.getBytes(), Base64.NO_WRAP);  // twitter ants the authorization in bytes

                    httppost.setHeader("Authorization", authorization);
                    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                    httppost.setEntity(new StringEntity("grant_type=client_credentials"));

                    InputStream inputStream = null;
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); // reading the input stream
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }

                    return sb.toString();
                }catch (Exception e){
                    Log.e("GetTokenTask", "Error:" + e.getMessage());
                    return null;
                }
            }

            @Override
            protected void onPostExecute(String jsonText){
                try {
                    JSONObject root = new JSONObject(jsonText);
                    String bearer_token = root.getString("access_token");

                    TextView txt = (TextView)findViewById(R.id.txt_token);
                    txt.setText(bearer_token);    
                }catch (Exception e){
                    Log.e("GetTokenTask", "Error:" + e.getMessage());
                }
            }
        }  

        protected class GetTweetsTask extends AsyncTask<String, Void, String> {   //the class is run as a thread in the background to get the tweets

            @Override
            protected String doInBackground(String... params) {

                try {
                    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                    HttpGet httpget = new HttpGet(params[1]);
                    httpget.setHeader("Authorization", "Bearer " + params[0]);

                    httpget.setHeader("Content-type", "application/json");   //json content type

                    InputStream inputStream = null;
                    HttpResponse response = httpclient.execute(httpget);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    return sb.toString();
                }catch (Exception e){
                    Log.e("GetFeedTask", "Error:" + e.getMessage());
                    return null;
                }
            }

            @Override
            protected void onPostExecute(String jsonString){
                try {
                    TextView txt_tweets = (TextView)findViewById(R.id.txt_tweets);

                    JSONObject forecastJson = new JSONObject(jsonString);
                    JSONArray forecastArray = forecastJson.getJSONArray("list");

                    String txt = "";

                    int i;

                    double minTemp, maxTemp;

                    // we are going to parse the json string and only display created_at and text. You can decide to display more objects if you want.
                    for (i=0;i<tweets.length();i++)
                    {

                            JSONObject dailyForecast = forecastArray.getJSONObject(i);
                            JSONObject tempObject = dailyForecast.getJSONObject("temp");
                            minTemp = tempObject.getDouble("min");
                            maxTemp = tempObject.getDouble("max");
                            //add these minTemp and maxTemp to array or the
                            //way you want to use


                        txt_tweets.setText(txt);

                        txt += "------------\n";  //separtors, check the output


                    }



                }catch (Exception e){
                    Log.e("GetFeedTask", "Error:" + e.getMessage());
                }
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.mytweets, menu);
            return true;

        }    

    }

This is the JSON format of weather data: 这是天气数据的JSON格式:

city: {
id: 2643743,
name: "London",
coord: {
lon: -0.12574,
lat: 51.50853
},
country: "GB",
population: 0
},
cod: "200",
message: 0.0268,
cnt: 5,
list: [
{
dt: 1448535600,
temp: {
day: 8.58,
min: 8.58,
max: 9.18,
night: 9.18,
eve: 8.58,
morn: 8.58
},
pressure: 1025.14,
humidity: 95,
weather: [
{
id: 500,
main: "Rain",
description: "light rain",
icon: "10d"
}
],
speed: 3.67,
deg: 224,
clouds: 92,
rain: 0.35
},
{},
{},
{},
{}
]

Now to access the weather data (eg min and max temp) you need to parse as below: 现在,要访问天气数据(例如,最低和最高温度),您需要进行如下分析:

JSONObject forecastJson = new JSONObject(jsonString);
JSONArray forecastArray = forecastJson.getJSONArray("list");
double minTemp, maxTemp;
for(int i = 0; i < forecastArray.length(); i++) {
    JSONObject dailyForecast = forecastArray.getJSONObject(i);
    JSONObject tempObject = dailyForecast.getJSONObject("temp");
    minTemp = tempObject.getDouble("min");
    maxTemp = tempObject.getDouble("max");
    //add these minTemp and maxTemp to array or the 
   //way you want to use
}

If you have further doubts, please let me know. 如果您还有其他疑问,请告诉我。

使用数组和对象,并确保您具有json解析器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM