第一步 新建一个文件夹 dao
用来存放我们待会要创建的文件
第二步 新建一个MySql类
这个类要继承 SQLiteOpenHelper
public class MySql extends SQLiteOpenHelper {
public MySql(Context context) {
super( context, "z3.db", null, 1 );
}
@Override
public void onCreate(SQLiteDatabase db) {
//建表--表里有两个字段 title 和 description
db.execSQL( "create table news(title text,description text)" );
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
第三步 新建一个Dao类
我们要用到的数据库查询和添加都写在这个Dao类里,定义了两个方法insert()和query(),我们可以在其他的页面调用到这两个方法
public class Dao {
private Context context;
private SQLiteDatabase db;
public Dao(Context context) {
this.context = context;
//新建mysql
MySql mySql = new MySql( context );
//对数据库进行操作
db = mySql.getWritableDatabase();
}
//数据库添加 的方法
public long insert(String table, String nullColumnHack, ContentValues values){
return db.insert( "news",null,values );
}
//数据库查询 的方法
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy){
return db.query( "news",null,null,null,null,null,null );
}
}
下面我会将我解析出来的集合添加到数据库中
先得到Dao层
Dao dao = new Dao( getActivity() );
调用dao层的insert添加方法
//解析数据--s
Gson gson = new Gson();
JsonBean bean = gson.fromJson( s, JsonBean.class );
//转变集合
list.addAll( bean.getNewslist() );
//添加到数据库中
ContentValues values=new ContentValues( );
for (int i = 0; i < list.size(); i++) {
values.put( "title",list.get( i ).getTitle() );
values.put( "description",list.get( i ).getDescription() );
insert = dao.insert( "news", null, values );
}//添加到数据库中
//刷新适配器
adapter.notifyDataSetChanged();