gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:44:21 25 4
gpt4 key购买 nike

我想从 API 中以 JSON 格式检索天气数据,但它不起作用。如何将天气数据(例如 5 天预报)拉入 TextView ?

我的代码在下面,但我需要以某种方式对其进行调整以传入 JSON 5 天天气预报并将其放入 TextView 中。

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;

}

}

最佳答案

这是天气数据的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
},
{},
{},
{},
{}
]

现在要访问天气数据(例如最低和最高温度),您需要按如下方式解析:

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
}

如果您还有其他疑问,请告诉我。

关于java - 如何在 json [android] 中检索天气数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33946702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com