轉載請標明出處
最近做一個聊天相關方法和存儲的依賴包,用到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鏈接