我在Android的eclipse中制作天气应用程序,我需要在1天之间显示描述天气的图标,间隔3小时。
我从http://api.openweathermap.org/data/2.5/forecast?q=Melbourne
获取API然后我使用http://www.jsonschema2pojo.org/在java类中创建(我认为这就是它的作用..)
现在我收到了以下代码:
private class ForecastForHoursTask extends AsyncTask<String, Integer, String> {
String measurement = checkMeasurement();
private final String SERVICE_ADDRESS_START = "http://api.openweathermap.org/data/2.5/forecast?q=";
ProgressBar progressBar;
public ForecastForHoursTask(ProgressBar progressBar) {
this.progressBar = progressBar;
progressBar.setProgress(0);
}
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
String serviceAddress = SERVICE_ADDRESS_START + params[0];
StringBuilder response = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(serviceAddress);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String bufferString = "";
while ((bufferString = buffer.readLine()) != null) {
response.append(bufferString);
}
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (this.progressBar != null) {
progressBar.setProgress(progress[0]);
}
}
@Override
protected void onPostExecute(String result) {
ImageView imgFirst = (ImageView) findViewById(R.id.imgEightAm);
ImageView imgSecond = (ImageView) findViewById(R.id.imgElevenAm);
ImageView imgThird = (ImageView) findViewById(R.id.imgTwoPm);
ImageView imgFourth = (ImageView) findViewById(R.id.imgFivePm);
ImageView imgFifth = (ImageView) findViewById(R.id.imgEightPm);
ImageView imgSixth = (ImageView) findViewById(R.id.imgElevenPm);
ImageView imgSeventh = (ImageView) findViewById(R.id.imgTwoAm);
ImageView imgEighth = (ImageView) findViewById(R.id.imgFiveAm);
TextView imgTest = (TextView) findViewById(R.id.lblTest);
Gson gson = new Gson();
NewRoot newitem = gson.fromJson(result, NewRoot.class);
progressBar.setProgress(0);
progressBar.setVisibility(-1);
}
}
我想要将图标设置为ImageView。但我很难在onPostExecute中做些什么。我想我需要对数据进行排序,以便我可以搜索(dt_txt)字段并获取相关的(图标)值,这样我就可以通过(icon)值将ImageView设置为相应的图像。 我坚持要怎么做。
答案 0 :(得分:0)
这可能是序列化问题。 NewRoot类中的名称和数据类型必须与从API下载的名称和数据类型相匹配。如果需要,您也可以使用Gson注释设置它们。 这是一本很棒的指南,你应该阅读:link。