Android 端天气预报APP的实现(五)全国各地城市数据的获取

2025-09-12 10:04:48 20阅读

获取了天气数据,接下来就是获取全国各地的城市数据了,我的整体思路是先将城市数据从服务器上获取下来,然后将其存储到数据库中。

首先,先准备数据库,创建三个表分别存储省市县。

**
 * Created by zhaoxin on 17/9/3.
 * 数据库
 */
public class MyDatabaseHelper extends SQLiteOpenHelper {
   
   
    //创建省份表
    private static final String CREATE_PROVINCE = "create table tb_province(" +
            "id integer primary key autoincrement," +
            "province_name varchar(20)," +
            "province_code integer)";
    //创建城市表
    private static final String CREATE_CITY = "create table tb_city(" +
            "id integer primary key autoincrement," +
            "city_name varchar(20)," +
            "city_code integer," +
            "province_id integer)";
    //创建县城表
    private static final String CREATE_COUNTY = "create table tb_county(" +
            "id integer primary key autoincrement," +
            "county_name varchar(20)," +
            "county_code integer," +
            "weather_id varchar(20)," +
            "city_id integer)";
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    /**
     * 创建数据库时执行里面的方法
     */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //执行创建表的操作
        sqLiteDatabase.execSQL(CREATE_PROVINCE);
        sqLiteDatabase.execSQL(CREATE_CITY);
        sqLiteDatabase.execSQL(CREATE_COUNTY);
    }
    /**
     * 更新数据库时执行的方法,手动更改数据库的版本
     * */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //如果表存在,删除表
        sqLiteDatabase.execSQL("drop table if exists tb_province");
        sqLiteDatabase.execSQL("drop table if exists tb_city");
        sqLiteDatabase.execSQL("drop table if exists tb_county");
        //再调用onCreate方法执行相关操作
        onCreate(sqLiteDatabase);
    }
}

然后,每个表对应一个实体类,因此,我们需要创建三个实体类。

Province.java

/**

免责声明:由于无法甄别是否为投稿用户创作以及文章的准确性,本站尊重并保护知识产权,根据《信息网络传播权保护条例》,如我们转载的作品侵犯了您的权利,请您通知我们,请将本侵权页面网址发送邮件到qingge@88.com,深感抱歉,我们会做删除处理。