转载请标明出处
最近做一个聊天相关方法和存储的依赖包,用到SQLite,做分页查询上遇到一些问题。所以单独提出Dao做了个demo测试,其中一些注释和命名如果感到奇怪请忽略。本人懒不想管。直接上代码和demo.
布局:activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.longe.dbtest.MainActivity"> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/et_content" android:hint="内容" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/et_num" android:hint="会话类型(0,1)" android:inputType="number" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_ins" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="插入"/> <Button android:id="@+id/btn_que" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询"/> <Button android:id="@+id/btn_queOne" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询一条数据"/> <Button android:id="@+id/btn_queIsExist" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询是否存在"/> <Button android:id="@+id/btn_queLast" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询最后一条"/> <Button android:id="@+id/btn_queLimit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="分页查询"/> <Button android:id="@+id/btn_queNum" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询个数"/> <Button android:id="@+id/btn_del" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="删除所有同类型"/> <Button android:id="@+id/btn_delContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="删除匹配内容"/> <Button android:id="@+id/btn_up" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="修改一条数据"/> <Button android:id="@+id/btn_upAllStatus" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="修改所有类型"/> <Button android:id="@+id/btn_delAll" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="删除所有"/> <TextView android:id="@+id/tv_content" android:textColor="#a91b1b" android:layout_margin="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> </LinearLayout>
MySQLiteOpenHelper.JAVA
package com.longe.dbtest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * MySQLiteOpenHelper * @author ZGQ * @version 1.0, 2017/6/6 0006 * @since */ public class MySQLiteOpenHelper extends SQLiteOpenHelper { private static String DATABASE_NAME = "im_message.db"; private static Integer version = 1; public static String TABLE_NAME_DBMESSAGE = "db_message"; public static String TABLE_NAME_DBCONTACT = "db_contact"; public static String TABLE_NAME_USERINFOMODEL = "user_info_model"; public MySQLiteOpenHelper(Context context) { super(context, DATABASE_NAME, null, version); } // String sql = "create table " + // "if not exists " + // TABLE_NAME +"(" + // "id Integer primary key autoincrement," + // "EMPLOYEE_NUM varchar"; @Override public void onCreate(SQLiteDatabase db) { //通过SQLiteDatabase执行一个创建表的sql语句 // db.execSQL(sql); // final String sqlStr = "create table if not exists " + TABLE_NAME + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_AGE + " integer," + KEY_PRICE + " float);"; // db.execSQL(sqlStr); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } }
IMDBMessageDao.java
package com.longe.dbtest; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * IMDBMessageDao 聊天消息 * * @author ZGQ * @version 1.0, 2017/6/6 0006 */ public class IMDBMessageDao { private static final String TABLE_NAME = MySQLiteOpenHelper.TABLE_NAME_DBMESSAGE;//数据表名称 //表的字段名 private static String KEY_ID = "id";//主键 private static String key_conversationId = "conversationId"; //所属会话的唯一标识符 private static String key_timestamp = "timestamp"; //消息时间戳 private static String key_chatType = "chatType"; //聊天类型 private static String key_body = "body"; //消息内容体 private SQLiteDatabase mDatabase; private Context mContext; private MySQLiteOpenHelper mDbOpenHelper;//数据库打开帮助类 public IMDBMessageDao(Context context) { mContext = context; openDataBase(); } //打开数据库 public void openDataBase() { if (mDbOpenHelper == null) { mDbOpenHelper = new MySQLiteOpenHelper(mContext); } try { mDatabase = mDbOpenHelper.getWritableDatabase();//获取可写数据库 } catch (SQLException e) { mDatabase = mDbOpenHelper.getReadableDatabase();//获取只读数据库 } createTable(); } /**** * 2.创建表 */ public void createTable() { String sql = "CREATE TABLE " + "IF NOT EXISTS " + TABLE_NAME + "(" + KEY_ID + " Integer PRIMARY KEY AUTOINCREMENT," + key_conversationId + " varchar," + key_timestamp + " integer," + key_chatType + " integer," + key_body + " varchar);"; mDatabase.execSQL(sql); } //插入一条数据 public void insertData(MessageBean bean) { ContentValues values = new ContentValues(); values.put(key_conversationId, bean.getConversationId()); values.put(key_timestamp, bean.getTimestamp()); values.put(key_chatType, bean.getChatType()); values.put(key_body, bean.getBody()); mDatabase.insert(TABLE_NAME, null, values); } //查询删除所匹配ID的数据 public void deleteData(String conversationId, long type) { Cursor cursor = null; try { cursor = mDatabase.query(TABLE_NAME, null, key_conversationId + "=?", new String[]{conversationId}, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { long chatType = cursor.getLong(cursor.getColumnIndex(key_chatType)); if (type == chatType) { mDatabase.delete(TABLE_NAME, key_chatType + "=? and " + key_conversationId + "=?", new String[]{chatType + "", conversationId}); } } } } catch (Exception e) { e.printStackTrace(); } } //按会话标识删除数据 public long delConversation(String conversationId) { return mDatabase.delete(TABLE_NAME, key_body + "=?", new String[]{conversationId}); } //更新一条数据 public long updateData(MessageBean bean) { ContentValues values = new ContentValues(); values.put(key_conversationId, bean.getConversationId()); values.put(key_timestamp, bean.getTimestamp()); values.put(key_chatType, bean.getChatType()); values.put(key_body, bean.getBody()); return mDatabase.update(TABLE_NAME, values, key_chatType + "=? and " + key_conversationId + "=?" , new String[]{bean.getChatType() + "", bean.getConversationId()}); } //更新一条数据 public long updateReadStatus(String converId, int type) { ContentValues values = new ContentValues(); values.put(key_chatType, type); return mDatabase.update(TABLE_NAME, values, key_conversationId + "=?" , new String[]{converId}); } //查询一条数据 public MessageBean queryData(String body, String conversationId) { MessageBean bean = new MessageBean(); Cursor cursor = null; try { String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+key_conversationId +"=? and " +key_body +"=?"; cursor = mDatabase.rawQuery(sql, new String[]{conversationId, body+""}); if (cursor != null) { if (cursor.moveToNext()) { bean.setConversationId(cursor.getString(cursor.getColumnIndex(key_conversationId))); bean.setTimestamp(cursor.getLong(cursor.getColumnIndex(key_timestamp))); bean.setChatType(cursor.getInt(cursor.getColumnIndex(key_chatType))); bean.setBody(cursor.getString(cursor.getColumnIndex(key_body))); } } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return bean; } //查询此会话是否存在 public boolean isExist(String conversationId) { boolean bean = false; Cursor cursor = null; try { String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+key_conversationId +"=?"; cursor = mDatabase.rawQuery(sql, new String[]{conversationId}); if (cursor != null) { if (cursor.moveToNext()) { bean = true; } } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return bean; } //查询所有数据 public List<MessageBean> queryAllData() { List<MessageBean> beans = new ArrayList<>(); MessageBean bean; Cursor cursor = null; try { cursor = mDatabase.rawQuery("SELECT * FROM " + TABLE_NAME, null); while (cursor.moveToNext()) { bean = new MessageBean(); bean.setConversationId(cursor.getString(cursor.getColumnIndex(key_conversationId))); bean.setTimestamp(cursor.getLong(cursor.getColumnIndex(key_timestamp))); bean.setChatType(cursor.getInt(cursor.getColumnIndex(key_chatType))); bean.setBody(cursor.getString(cursor.getColumnIndex(key_body))); beans.add(bean); } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return beans; } /** * 根据会话分页查询数据 * * @param size 查询分页大小 * @param page index 分页下标 算法 [第一页:(1-1)*size] [第二页:(2-1)*size] * @param conversationId 会话标识 * @return */ public List<MessageBean> queryConversation(int size, int page, String conversationId, int chatType) { int index = page * size; List<MessageBean> locaBeen = new ArrayList<>(); MessageBean bean = null; Cursor cursor = null; try { String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+key_conversationId +"=? and " +key_chatType +"=?"+" order by "+key_timestamp+" desc limit "+index+","+size; cursor = mDatabase.rawQuery(sql, new String[]{conversationId, chatType+""}); if (cursor != null) { while (cursor.moveToNext()) { bean = new MessageBean(); bean.setConversationId(cursor.getString(cursor.getColumnIndex(key_conversationId))); bean.setTimestamp(cursor.getLong(cursor.getColumnIndex(key_timestamp))); bean.setChatType(cursor.getInt(cursor.getColumnIndex(key_chatType))); bean.setBody(cursor.getString(cursor.getColumnIndex(key_body))); locaBeen.add(bean); } } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return locaBeen; } /** * 按照会话标识查询数据 * * @param conversationId 会话标识 * @return */ public List<MessageBean> queryConversation(String conversationId) { List<MessageBean> locaBeen = new ArrayList<>(); MessageBean bean = null; Cursor cursor = null; try { String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+key_conversationId +"=?"; cursor = mDatabase.rawQuery(sql, new String[]{conversationId}); if (cursor != null) { while (cursor.moveToNext()) { bean = new MessageBean(); bean.setConversationId(cursor.getString(cursor.getColumnIndex(key_conversationId))); bean.setTimestamp(cursor.getLong(cursor.getColumnIndex(key_timestamp))); bean.setChatType(cursor.getInt(cursor.getColumnIndex(key_chatType))); bean.setBody(cursor.getString(cursor.getColumnIndex(key_body))); locaBeen.add(bean); } } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return locaBeen; } /** * 按照会话标识查询未读 * * @param conversationId 会话标识 * @return */ public int queryUnRead(String conversationId) { int isRead = 0; Cursor cursor = null; try { String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+key_conversationId +"=? and " +key_chatType +"=?"; cursor = mDatabase.rawQuery(sql, new String[]{conversationId, 0+""}); if (cursor != null) { while (cursor.moveToNext()) { isRead++; } } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return isRead; } /** * 按照会话标识查询最后一条 * * @param conversationId 会话标识 * @return */ public MessageBean queryLastMessage(String conversationId, int chatType) { MessageBean bean = new MessageBean(); Cursor cursor = null; try { String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+key_conversationId +"=? and " +key_chatType +"=?"+" order by "+key_timestamp+" desc limit "+0+","+1; cursor = mDatabase.rawQuery(sql, new String[]{conversationId, chatType+""}); if (cursor != null) { while (cursor.moveToNext()) { bean.setConversationId(cursor.getString(cursor.getColumnIndex(key_conversationId))); bean.setTimestamp(cursor.getLong(cursor.getColumnIndex(key_timestamp))); bean.setChatType(cursor.getInt(cursor.getColumnIndex(key_chatType))); bean.setBody(cursor.getString(cursor.getColumnIndex(key_body))); } } } catch (Exception e) { e.printStackTrace(); } cursor.close(); return bean; } //删除所有数据 public long cleanAllData() { return mDatabase.delete(TABLE_NAME, null, null); } //关闭数据库 public void closeDataBase() { if (mDatabase != null) { mDatabase.close(); } } }
MessageBean.java
package com.longe.dbtest; /** * MessageBean 消息表 bean * * @author ZGQ * @version 1.0, 2017/6/6 0006 */ public class MessageBean { private String conversationId; //所属会话的唯一标识符 private long timestamp; //消息时间戳 private int chatType; //聊天类型 private String body; //消息内容体 public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public int getChatType() { return chatType; } public void setChatType(int chatType) { this.chatType = chatType; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
MainActivity.java
package com.longe.dbtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.List; public class MainActivity extends AppCompatActivity { private int chatType; private int page; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final IMDBMessageDao imdbMessageDao = new IMDBMessageDao(this); imdbMessageDao.openDataBase(); final EditText etContent = (EditText) findViewById(R.id.et_content); Button btnIns = (Button) findViewById(R.id.btn_ins); final Button btn_del = (Button) findViewById(R.id.btn_del); final Button btn_delContent = (Button) findViewById(R.id.btn_delContent); Button btn_up = (Button) findViewById(R.id.btn_up); Button btn_upAllStatus = (Button) findViewById(R.id.btn_upAllStatus); Button btn_que = (Button) findViewById(R.id.btn_que); Button btn_queOne = (Button) findViewById(R.id.btn_queOne); Button btn_queIsExist = (Button) findViewById(R.id.btn_queIsExist); Button btn_queLast = (Button) findViewById(R.id.btn_queLast); Button btn_queLimit = (Button) findViewById(R.id.btn_queLimit); Button btn_delAll = (Button) findViewById(R.id.btn_delAll); final Button btn_queNum = (Button) findViewById(R.id.btn_queNum); final TextView tvContent = (TextView) findViewById(R.id.tv_content); final EditText etNum = (EditText) findViewById(R.id.et_num); final String id = "asdfsadfa"; chatType = 0; //增 btnIns.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MessageBean bean = new MessageBean(); bean.setBody(etContent.getText().toString().trim()); bean.setChatType(Integer.valueOf(etNum.getText().toString().trim())); bean.setConversationId(id); bean.setTimestamp(System.currentTimeMillis()); imdbMessageDao.insertData(bean); } }); //删除所有同类型 btn_del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imdbMessageDao.deleteData(id, Integer.valueOf(etNum.getText().toString().trim())); } }); //删除匹配内容 btn_delContent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imdbMessageDao.delConversation(etContent.getText().toString().trim()); } }); //修改一条数据 btn_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MessageBean bean = new MessageBean(); bean.setConversationId(id); bean.setChatType(1); bean.setTimestamp(System.currentTimeMillis()); bean.setBody(etContent.getText().toString().trim()); imdbMessageDao.updateData(bean); } }); //修改所有类型 btn_upAllStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imdbMessageDao.updateReadStatus(id, Integer.valueOf(etNum.getText().toString().trim())); } }); //查所有 btn_que.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<MessageBean> messageBeen = imdbMessageDao.queryConversation(id); StringBuilder s = new StringBuilder(); for (int i = 0; i < messageBeen.size(); i++) { s.append(messageBeen.get(i).getBody() + "<" + messageBeen.get(i).getChatType() + ">" + "~、、~"); } page = 0; tvContent.setText(s); } }); //查寻一条数据 btn_queOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MessageBean messageBeen = imdbMessageDao.queryData(etContent.getText().toString().trim(), id); page = 0; tvContent.setText(messageBeen.getBody() + "<" + messageBeen.getChatType() + ">"); } }); //查寻是否存在 btn_queIsExist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean exist = imdbMessageDao.isExist(id); page = 0; tvContent.setText(exist +">"); } }); //查寻最后一条 btn_queLast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MessageBean messageBean = imdbMessageDao.queryLastMessage(id, Integer.valueOf(etNum.getText().toString().trim())); page = 0; tvContent.setText(messageBean.getBody() +"<"+messageBean.getChatType()+">"); } }); page = 0; //分页查询 btn_queLimit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<MessageBean> messageBeen = imdbMessageDao.queryConversation(3, page, id, chatType); StringBuilder s = new StringBuilder(); for (int i = 0; i < messageBeen.size(); i++) { s.append(messageBeen.get(i).getBody() + "~、、~"); } tvContent.setText(s); page++; } }); //查询个数 btn_queNum.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int unRead = imdbMessageDao.queryUnRead(id); tvContent.setText(unRead + ""); } }); //删除所有 btn_delAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imdbMessageDao.cleanAllData(); } }); } }
以上是全部代码
这是DEMO链接