您好,登录后才能下订单哦!
以论坛为例,只缓存最新的20条帖子 用到sqlite
流程:1. 创建数据库文件和表
db.execSQL("CREATE TABLE table"
"(_id INTEGER PRIMARY KEY AUTOINCREMENT,subject VARCHAR(200),author VARCHAR(20), dateline VARCHAR(20),replies VARCHAR(20),tid VARCHAR(20)";
2. 查询、插入、删除
//插入
public static void insert(SQLiteDatabase db, ContentValues values)
{
db.insert(”reclist“, null, values);
}
//删除
public static void delete(SQLiteDatabase db)
{
db.delete(”reclist“, null, null);
}
//查询前先建PostInfo封装类,把得到的数据添加到ArrayList容器里
//查询
public static ArrayList<PostInfo> query(SQLiteDatabase db)
{
Cursor cursor = db.query("reclist", null, null, null,
null, null, null);
ArrayList<PostInfo> data = new ArrayList<PostInfo>();
boolean hasNext = cursor.moveToFirst();
while (hasNext)
{
String author = cursor.getString(cursor
.getColumnIndex("author "));
String dateline = cursor.getString(cursor
.getColumnIndex("dateline"));
String replies = cursor.getString(cursor
.getColumnIndex("replies"));
String subject = cursor.getString(cursor
.getColumnIndex("subject"));
int tid = cursor.getInt(cursor
.getColumnIndex("tid"));
PostInfo info = new PostInfo(subject, author, dateline, replies,
tid);
data.add(info);
hasNext = cursor.moveToNext();
}
cursor.close();
return data;
}
3. 得到最新20条时,删除数据库表的内容 ,再插入
4. 启动时查询数据库
5. 如果有网络,从网络获取最新内容后,清空ListView,使用最新内容
//把查询到的内容添加到集合去
ArrayList<PostInfo> query = DataBaseUtils.query(mDB);
if (query.size() > 0)
{
mPostInfoList.addAll(query);
}
//在jsonArray解析的时候删除前面的内容
JSONArray array = new JSONArray(result);
if (array.length() > 0 && mPage == 1)
{
mPostInfoList.clear();
}
for (int i = 0; i < array.length(); i++)
{
JSONObject jsonObject = array.getJSONObject(i);
int tid = jsonObject.getInt("tid");
String hottopic_title = jsonObject.getString("subject");
String hottopic_name = jsonObject.getString("author");
String hottopic_shijian = jsonObject.getString("dateline");
String hottopic_huiying = jsonObject.getString("replies");
downloadData = new PostInfo(hottopic_title, hottopic_name,
hottopic_shijian, hottopic_huiying, tid);
mPostInfoList.add(downloadData);
}
if (mPage == 1)
{
// 删除旧的数据
DataBaseUtils.delete(mDB);
// 将最新20条保存到数据库中
for (int i = 0; i < mPostInfoList.size(); i++)
{
PostInfo info = mPostInfoList.get(i);
ContentValues values = new ContentValues();
values .put(TABLE_RECLIST.COLUMN_AUTHOR, info.getAuthor());
values.put(TABLE_RECLIST.COLUMN_DATELINE, info.getDateline());
values.put(TABLE_RECLIST.COLUMN_REPLIES, info.getReplies());
values.put(TABLE_RECLIST.COLUMN_SUBJECT, info.getSubject());
values.put(TABLE_RECLIST.COLUMN_TID, info.getTid());
DataBaseUtils.insert(mDB, values );
}
}
mAdapter.notifyDataSetChanged();
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。