Android天气预报

1.Android的天气预报的应用还是挺多的,基于JSON和WebServ的均可。首先我们来介绍基于JSON解析的天气预报的开发
2.这需要寻找到合适的数据源。这里使用的是http://www.weather.com.cn/(中央气象局)的数据信息。可通过m.weather.com.cn/data/101010100.html或者www.weather.com.cn/data/cityinfo/101010100.html。
查看到北京的天气信息
Android天气预报_第1张图片
3.接下来就是对JSON数据的解析

package com.cater.weather;



import java.io.IOException;



import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;



public class WeatherReportActivity extends Activity
{
private final static String url = "http://m.weather.com.cn/data/101010100.html";
private HttpClient httpClient;
private HttpResponse httpResponse;
private HttpGet httpGet;
private EditText editText;
private TextView textView;
private String today;
private String dayofweek;
private String city;
private int ftime;
private String template;



@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView1);
httpClient = new DefaultHttpClient();
parseString(getRequest(url));
editText.setText(getRequest(url));
textView.setText("城市:" + city + "\n"
+"温度:" + template + "\n"
+"星期:" + dayofweek + "\n"
+"时间:" + ftime + "\n"
+"日期:" + today + "\n");
}

private String getRequest(String uri)
{
httpGet = new HttpGet(uri);
String result = "";

try
{
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

return null;
}

private String parseString(String str)
{
try
{
JSONObject jsonObject = new JSONObject(str).getJSONObject("weatherinfo");
today = jsonObject.getString("date_y");
dayofweek = jsonObject.getString("week");
city = jsonObject.getString("city");
ftime = jsonObject.getInt("fchh");
template = jsonObject.getString("temp1");
}
catch (JSONException e)
{
e.printStackTrace();
}

return null;
}



}
```


声明:eoe文章著作权属于作者,受法律保护,转载时请务必以超链接形式附带如下信息

原文作者: Cater

原文地址: http://my.eoe.cn/816623/archive/1949.html

你可能感兴趣的:(Android,Android,JSON,网络)