sqlite Android实现本地缓存

前端之家收集整理的这篇文章主要介绍了sqlite Android实现本地缓存前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

简述:

用到一款聊天框架,需要实现sqlite本地缓存聊天历史,试用sqlite实现本地缓存


步骤:

1. 建立表

public class TableInfo {
	public class SingleChatTable {
		public static final String TABLENAME= "SingleChatTable";//表名
		public static final String FROMJID = "fromJid"; //聊天发送者的Jid
		public static final String TOJID = "toJID";//聊天接受者的Jid
		public static final String BODY = "body";//如果是聊天室,那么聊天室创建人
		public static final String SENDTIME = "sendTime";//发送时间
		public static final String IS_READ = "isRead";//是否查看过
		/** 表默认的_id*/
		public static final String ID ="id";
		/**得到创建表的sql语句*/
		public  static final String CREATETABLEsql = "CREATE TABLE IF NOT EXISTS "+ TABLENAME +" (" 
		        + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," 
				+ FROMJID +" TEXT,"
				+ TOJID +" TEXT,"
				+ BODY +" TEXT,"
				+ SENDTIME +" TEXT,"
				+ IS_READ +" INTEGER"
						+" )";
		/**得到删除表的sql语句*/
		public static final String DELETETABLEsql = "DROP TABLE IF EXISTS "+ TABLENAME;
	}
}


2. 数据库操作类

public class DBHelper extends sqliteOpenHelper {

	private static final String TAG = "DBHelper";
	
	public static final String DB_NAME = "aimp.db";
	public static final int DB_VERSION = 1;
	public Context mContext;

	public DBHelper(Context context) {
		super(context,DB_NAME,null,DB_VERSION);
		this.mContext = context;
	}

	
	public DBHelper(Context context,String name,CursorFactory factory,int version) {
		super(context,name,factory,version);
	}

	
	@Override
	public void onCreate(sqliteDatabase db) {
		db.execsql(TableInfo.SingleChatTable.CREATETABLEsql);
	}

	
	@Override
	public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
		db.execsql(TableInfo.SingleChatTable.DELETETABLEsql);
		onCreate(db);
	}


	/**
	 * 获取fromJid与toJid之间的聊天记录列表
	 * @param fromJid
	 * @param toJid
	 * @return
	 */
	public List<SingleChatItem> obtainSingleChatList(String fromJid,String toJid){
		List<SingleChatItem> list = new LinkedList<SingleChatItem>();
		
		sqliteDatabase db = null;
		Cursor cursor = null;
		
		try {
			db = getReadableDatabase();
			// 根据fromJid和toJid获取聊天记录
			String selection = "( " + TableInfo.SingleChatTable.FROMJID + "=\""
					+ fromJid + "\" and "
					+ TableInfo.SingleChatTable.TOJID + "=\""
					+ toJid + "\") or (" 
					+ TableInfo.SingleChatTable.TOJID + "=\""
					+ fromJid + "\" and "
					+ TableInfo.SingleChatTable.FROMJID + "=\""
					+ toJid + "\")";
			// 按照ID获取聊天记录
			cursor = db.query(true,TableInfo.SingleChatTable.TABLENAME,selection,TableInfo.SingleChatTable.ID + " ASC",null);

			if (cursor.moveToFirst()) {
				do {
					SingleChatItem msg = new SingleChatItem();
					// 要注意拿数据的顺序,游标不能回头
					msg.setFromJid(cursor.getString(cursor
							.getColumnIndex(TableInfo.SingleChatTable.FROMJID)));
					msg.setToJid(cursor.getString(cursor
							.getColumnIndex(TableInfo.SingleChatTable.TOJID)));
					msg.setBody(cursor.getString(cursor
							.getColumnIndex(TableInfo.SingleChatTable.BODY)));
					msg.setSendTime(cursor.getString(cursor
							.getColumnIndex(TableInfo.SingleChatTable.SENDTIME)));
					list.add(msg);
				} while (cursor.moveToNext());
			}
			Log.i(TAG,"获取单人聊天记录的记录数: " + String.valueOf(list.size()));
		} catch (Exception e) {
			Log.e(TAG,"获取单人聊天记录失败! ");
		} finally {
			if (cursor != null) {
				try {
					cursor.close();
					cursor = null;
				} catch (Exception e) {
				}
			}
			if (db != null) {
				try {
					db.close();
					db = null;
				} catch (Exception e) {
				}
			}
		}
		return list;
	}
	
	
	/**
	 * 将单聊类转换为ContentValues
	 * @return
	 */
	private ContentValues getContentValuesByChatItem(SingleChatItem item,boolean isRead){
		if (item == null) {
			Log.e(TAG,"getContentValuesByChatItem 转换失败,数据为空");
		}
		ContentValues values = new ContentValues();
		// 聊天发送方的JID
		values.put(TableInfo.SingleChatTable.FROMJID,item.getFromJid());
		// 聊天接受方的JID
		values.put(TableInfo.SingleChatTable.TOJID,item.getToJid());
		// 发送时间
		values.put(TableInfo.SingleChatTable.SENDTIME,item.getSendTime());
		// 发送的内容
		values.put(TableInfo.SingleChatTable.BODY,item.getBody());
		// 是否已读
		values.put(TableInfo.SingleChatTable.IS_READ,item.isRead());
		return values;
	}
	
	
	/**
	 * 插入一条单人聊天聊天记录
	 * @param item
	 * @param isRead
	 * @return
	 */
	public boolean insertSingleChat(SingleChatItem item,boolean isRead){
		boolean result = true;
		
		sqliteDatabase db = null;
		try {
			db = getWritableDatabase();
			db.beginTransaction();
			
			ContentValues values = getContentValuesByChatItem(item,isRead);
			long operating = 0;
			operating = db.insert(TableInfo.SingleChatTable.TABLENAME,values);

			if (operating < 0) {
				result = false;
			}
		} catch (Exception e) {
			result = false;
			Log.e(TAG,String.valueOf(e));
		} finally {
			if (db != null && db.isOpen()) {
				db.setTransactionSuccessful();
				db.endTransaction();
				db.close();
			}
		}
		return result;
	}

	
}

聊天对象
import android.text.TextUtils;

public class SingleChatItem {
	private String fromJid;
	private String toJid;
	private String body;
	private String sendTime;
	private boolean isRead;
	public String getFromJid() {
		return fromJid;
	}
	public void setFromJid(String fromJid) {
		if(!TextUtils.isEmpty(fromJid) && fromJid.split("/").length>0)
			this.fromJid = fromJid.split("/")[0];
		else
			this.fromJid = fromJid;
	}
	public String getToJid() {
		return toJid;
	}
	public void setToJid(String toJid) {
		if(!TextUtils.isEmpty(toJid) && toJid.split("/").length > 0)
			this.toJid = toJid.split("/")[0];
		else
			this.toJid = toJid;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
	public String getSendTime() {
		return sendTime;
	}
	public void setSendTime(String sendTime) {
		this.sendTime = sendTime;
	}
	public boolean isRead() {
		return isRead;
	}
	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}
}

之后再试用db的时候传入context就可以用了
dbHelper = new DBHelper(this);

猜你在找的Sqlite相关文章