你好,游客 登录 注册 搜索
背景:
阅读新闻

Android简单的获取不同城市实时天气预报【附源码】

[日期:2013-07-07] 来源:Linux社区  作者:Forsta [字体:大 中 小]

4.主类 如下

具体说明见注释

package com.cityselection;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import Android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class City_SelectionActivity extends Activity {
/** Called when the activity is first created. */

private File f = new File("/sdcard/weather/db_weather.db"); //数据库文件
private File f1 = new File("/sdcard/weather/DemoCity.db"); //数据库文件
private Spinner province; //省份spinner
private Spinner city; //城市spinner

private Button saveCity;

private TextView citynameshow;
private TextView temp;
private TextView wind;

private List<String> proset=new ArrayList<String>();//省份集合
private List<String> citset=new ArrayList<String>();//城市集合

private int pro_id;
private String cityname;
private long city_num;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(!f1.exists()){
try {
f1.createNewFile();
SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(f1, null);
db.execSQL("create table democity(city_id LONG,name Text)");
db.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
citynameshow=(TextView)findViewById(R.id.city_name);
temp=(TextView)findViewById(R.id.temp);
wind=(TextView)findViewById(R.id.wind);

saveCity=(Button)findViewById(R.id.savecity);
saveCity.setOnClickListener(new SaveCity());

province=(Spinner)findViewById(R.id.provinces);
ArrayAdapter<String> pro_adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,getProSet());
province.setAdapter(pro_adapter);
province.setOnItemSelectedListener(new SelectProvince());

city=(Spinner)findViewById(R.id.city);
city.setOnItemSelectedListener(new SelectCity());

InitInfo();

}
/**
*
* 读取备份数据文件 显示天气
*
*/
class SaveCity implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
SQLiteDatabase db1=SQLiteDatabase.openOrCreateDatabase(f1, null);
db1.execSQL("delete from democity");
db1.execSQL("insert into democity values("+city_num+",'"+cityname+"')");
db1.close();

String url="http://www.weather.com.cn/data/sk/"+city_num+".html";
HttpDownloader httpdownloader=new HttpDownloader();
String json=httpdownloader.download(url);
Gson gson=new Gson();
WeatherModel wm=gson.fromJson(json, WeatherModel.class);
citynameshow.setText(wm.getWeatherinfo().getCity());
temp.setText("实时温度:"+wm.getWeatherinfo().getTemp()+"℃");
wind.setText("风向:"+wm.getWeatherinfo().getWD()+" "+wm.getWeatherinfo().getWS());


}
}
//选择改变状态
class SelectProvince implements OnItemSelectedListener{
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//获得省份ID
pro_id=position;
city.setAdapter(getAdapter());

}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}

//城市 选择改变状态
class SelectCity implements OnItemSelectedListener{
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
cityname=parent.getItemAtPosition(position).toString();
city_num=getCityNum(position);
//选择提示
Toast.makeText(getApplicationContext(), cityname+" "+city_num, 2000).show();


}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}

/**
* 返回 省份集合
*/
public List<String> getProSet(){
//打开数据库
if(f.exists()){
SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
Cursor cursor=db1.query("provinces", null, null, null, null, null, null);
while(cursor.moveToNext()){
String pro=cursor.getString(cursor.getColumnIndexOrThrow("name"));
proset.add(pro);
}
cursor.close();
db1.close();
}
else{
System.out.println("请检查数据库是否放到指定位置");
}
return proset;
}
/**
* 返回 城市集合
*/
public List<String> getCitSet(int pro_id){
//清空城市集合
citset.clear();
//打开数据库
SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
Cursor cursor=db1.query("citys", null, "province_id="+pro_id, null, null, null, null);
while(cursor.moveToNext()){
String pro=cursor.getString(cursor.getColumnIndexOrThrow("name"));
citset.add(pro);
}
cursor.close();
db1.close();
return citset;
}
/**
* 返回适配器
*/
public ArrayAdapter<String> getAdapter(){
ArrayAdapter<String> adapter1=new ArrayAdapter(this, android.R.layout.simple_spinner_item,getCitSet(pro_id));
return adapter1;
}
/**
* 返回城市编号 以便调用天气预报api
*/
public long getCityNum(int position){

SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
Cursor cursor=db1.query("citys", null, "province_id="+pro_id, null, null, null, null);
cursor.moveToPosition(position);
long citynum=Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow("city_num")));
cursor.close();
db1.close();
return citynum;


}
/**
* 初始化界面信息
*/
public void InitInfo(){

SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f1, null);
Cursor cursor=db1.query("democity", null, null, null, null, null, null);
if(cursor.getCount()!=0)
{
cursor.moveToFirst();
String citynum=cursor.getString(cursor.getColumnIndexOrThrow("city_id"));
cursor.close();
db1.close();
String url="http://www.weather.com.cn/data/sk/"+citynum+".html";
HttpDownloader httpdownloader=new HttpDownloader();
String json=httpdownloader.download(url);
Gson gson=new Gson();
WeatherModel wm=gson.fromJson(json, WeatherModel.class);
citynameshow.setText(wm.getWeatherinfo().getCity());
temp.setText("实时温度:"+wm.getWeatherinfo().getTemp()+"℃");
wind.setText("风向:"+wm.getWeatherinfo().getWD()+" "+wm.getWeatherinfo().getWS());
}
else{
cursor.close();
db1.close();
}
}

/**
* 下载json数据
*/
public class HttpDownloader {

private URL url = null;

/**
* 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容
* 1.创建一个URL对象
* 2.通过URL对象,创建一个HttpURLConnection对象
* 3.得到InputStream
* 4.从InputStream当中读取数据
* @param urlStr
* @return
*/
public String download(String urlStr){
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while( (line = buffer.readLine()) != null){
sb.append(line);
}

}
catch (Exception e) {
e.printStackTrace();
}
finally{
try {
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

}

结果:

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android获取天气预报 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款