【玩轉SQLite系列】(六)SQLite數據庫應用案例實現歷史搜索記錄

轉載請註明出處:http://blog.csdn.net/linglongxin24/article/details/53366564
本文出自【DylanAndroid的博客】


【玩轉SQLite系列】(六)SQLite數據庫應用案例實現歷史搜索記錄

前面通過一系列的文章講述了SQLite的各種使用場景,那麼我們用一個實際的案例去實現一個搜索歷史記錄的功能。
這裏面用到了以下內容:

【Android自定義View實戰】之自定義超簡單SearchView搜索框

Android寬度全屏的Dialog和DialogFragment用法

Java泛型應用之打造Android萬能ViewHolder-超簡潔寫法

Java泛型應用之打造Android中ListView和GridView萬能適配器【CommonAdapter】–超簡潔寫法

不瞭解的可以去學習一下。

一.編寫一個歷史搜索記錄實例對象

package cn.bluemobi.dylan.sqlite;

import java.util.Date;

/**
 * 搜索記錄的操作對象
 * Created by Administrator on 2016-11-20.
 */

public class History {
    /**
     * id 主鍵,自增
     */
    private int id;
    /**
     * 搜索的內容
     */
    private String content;
    /**
     * 搜索的時間
     */
    private String time;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

二.編寫一個操作數據庫的管理工具類

package cn.bluemobi.dylan.sqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 數據庫操作管理類
 * Created by Administrator on 2016-11-19.
 */

public class DBManager {
    private static volatile DBManager dbManager;
    private SQLiteDatabase sqLiteDatabase;

    private DBManager() {
        openDataBase();
        createTable();
    }

    public static DBManager getDBManager() {
        if (dbManager == null) {
            synchronized (DBManager.class) {
                if (dbManager == null) {
                    dbManager = new DBManager();
                }
            }
        }
        return dbManager;
    }

    /**
     * 數據庫名稱
     */
    private final String DATABASE_NAME = "info.db";
    /**
     * 表名
     */
    private final String TABLE_NAME = "history";

    /**
     * 表格所包含的字段
     */
    private class HistoryDbColumn {

        /**
         * 字段一 id
         */
        public static final String ID = "id";
        /**
         * 字段二 內容
         */
        public static final String CONTENT = "name";
        /**
         * 字段三 時間
         */
        public static final String TIME = "time";
    }

    /**
     * 1.創建或打開數據庫連接
     **/
    private void openDataBase() {
        File dataBaseFile = new File(Environment.getExternalStorageDirectory() + "/sqlite", DATABASE_NAME);
        if (!dataBaseFile.getParentFile().exists()) {
            dataBaseFile.mkdirs();
        }
        sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dataBaseFile, null);
    }

    /****
     * 2.創建表
     */
    private void createTable() {
        String sql = "CREATE TABLE " +
                "IF NOT EXISTS " +
                TABLE_NAME + "(" +
                HistoryDbColumn.ID + " Integer PRIMARY KEY AUTOINCREMENT," +
                HistoryDbColumn.CONTENT + " varchar," +
                HistoryDbColumn.TIME + " datetime)";
        sqLiteDatabase.execSQL(sql);
    }

    /**
     * 插入一條數據
     *
     * @param history
     * @return
     */
    public long insert(History history) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(HistoryDbColumn.CONTENT, history.getContent());
        contentValues.put(HistoryDbColumn.TIME, history.getTime());
        long num = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
        return num;
    }

    /**
     * 根據id刪除一條數據
     *
     * @param id
     * @return
     */
    public long delete(int id) {
        long num = sqLiteDatabase.delete(TABLE_NAME, HistoryDbColumn.ID + "=?", new String[]{String.valueOf(id)});
        return num;
    }

    /**
     * 根據id修改一條數據
     *
     * @param id
     * @return
     */
    public long update(History history, int id) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(HistoryDbColumn.CONTENT, history.getContent());
        contentValues.put(HistoryDbColumn.TIME, history.getTime());
        long num = sqLiteDatabase.update(TABLE_NAME, contentValues, HistoryDbColumn.ID + "=?", new String[]{String.valueOf(id)});
        return num;
    }

    /**
     * 根據id查詢一條數據
     *
     * @param id
     * @return
     */
    public History qurey(int id) {
        History history = null;
        Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, HistoryDbColumn.ID + "=?", new String[]{String.valueOf(id)}, null, null, null);
        if (cursor != null) {
            if (cursor.moveToNext()) {
                history = new History();
                history.setId(cursor.getInt(cursor.getColumnIndex(HistoryDbColumn.ID)));
                history.setContent(cursor.getString(cursor.getColumnIndex(HistoryDbColumn.CONTENT)));
                history.setTime(cursor.getString(cursor.getColumnIndex(HistoryDbColumn.TIME)));
            }
        }

        return history;
    }

    /**
     * 根據id查詢一條數據
     * 倒序
     *
     * @return
     */
    public List<History> queryAll() {
        List<History> historys = new ArrayList<>();
        Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, HistoryDbColumn.TIME + " desc");
        if (cursor != null) {
            while (cursor.moveToNext()) {
                History history = new History();
                history.setId(cursor.getInt(cursor.getColumnIndex(HistoryDbColumn.ID)));
                history.setContent(cursor.getString(cursor.getColumnIndex(HistoryDbColumn.CONTENT)));
                history.setTime(cursor.getString(cursor.getColumnIndex(HistoryDbColumn.TIME)));
                historys.add(history);
            }
        }
        return historys;
    }

    /**
     * 根據內容查詢一條數據
     *
     * @return
     */
    public History queryByContent(String content) {
        History history = null;
        Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, HistoryDbColumn.CONTENT + "=?", new String[]{content}, null, null, null);
        if (cursor != null) {
            if (cursor.moveToNext()) {
                history = new History();
                history.setId(cursor.getInt(cursor.getColumnIndex(HistoryDbColumn.ID)));
                history.setContent(cursor.getString(cursor.getColumnIndex(HistoryDbColumn.CONTENT)));
                history.setTime(cursor.getString(cursor.getColumnIndex(HistoryDbColumn.TIME)));
            }
        }
        return history;
    }
}

三.搜索對話框的佈局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="250dp"
    android:orientation="vertical">

    <cn.bluemobi.dylan.sqlite.SearchView
        android:id="@+id/sv"
        android:padding="10dp"
        android:background="@color/colorPrimaryDark"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </cn.bluemobi.dylan.sqlite.SearchView>

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

    <TextView
        android:id="@+id/tv"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="暫無搜索記錄" />
</LinearLayout>

四.編寫功能代碼

package cn.bluemobi.dylan.sqlite;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;
import java.util.List;

import cn.bluemobi.dylan.sqlite.adapter.CommonAdapter;
import cn.bluemobi.dylan.sqlite.adapter.CommonViewHolder;

/**
 * SQLite應用案例實現搜索記錄
 * Created by Administrator on 2016-11-20.
 */

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et;
    private ListView lv;
    private TextView tv;
    private Dialog dialog;
    private SearchView sv;
    private Button bt;
    private List<History> histories;
    private CommonAdapter<History> commonAdapter;
    private final int MAX_ITME = 5;

    private void assignViews() {
        et = (EditText) findViewById(R.id.et);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setTitle("SQLite應用案例實現搜索記錄");
        setContentView(R.layout.ac_search);
        assignViews();
        intiDialog();
        addListener();
        initData();
    }

    /**
     * 添加按鈕監聽
     */
    private void addListener() {
        et.setOnClickListener(this);
    }

    /***
     * 初始化搜索對話框
     */
    private void intiDialog() {
        dialog = new Dialog(this, R.style.Dialog_FullScreen);
        dialog.setContentView(R.layout.dialog_search);
        dialog.getWindow().setGravity(Gravity.TOP);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(lp);
        lv = (ListView) dialog.findViewById(R.id.lv);
        tv = (TextView) dialog.findViewById(R.id.tv);
        sv = (SearchView) dialog.findViewById(R.id.sv);
        bt = (Button) dialog.findViewById(R.id.bt);
        bt.setOnClickListener(this);
        lv.setEmptyView(tv);
    }

    /**
     * 初始化數據
     */
    private void initData() {
        commonAdapter = new CommonAdapter<History>(this, histories, R.layout.item_for_search) {
            @Override
            protected void convertView(CommonViewHolder commonViewHolder, History history) {
                TextView tv = commonViewHolder.get(R.id.textView);
                tv.setText(history.getContent());
            }
        };
        lv.setAdapter(commonAdapter);
        notifyAdapter();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et:
                if (!dialog.isShowing()) {
                    dialog.show();
                }
                break;
            case R.id.bt:
                addHistory();
                break;
        }

    }

    /**
     * 點擊搜索按鈕新增一條記錄
     */
    private void addHistory() {
        String inputText = sv.getInputText();
        if (inputText.isEmpty()) {
            Toast.makeText(this, "請輸入內容進行搜索", Toast.LENGTH_SHORT).show();
            return;
        }
        /**1.先判斷數據庫當中有沒有這條歷史記錄,如果有則修改其搜索的時間即可*/
        History history = DBManager.getDBManager().queryByContent(inputText);
        if (history != null) {
            history.setTime(new Date().toString());
            DBManager.getDBManager().update(history, history.getId());
        } else {
            /**2.判斷搜索記錄是否達到限值,達到極限則刪除一條數據**/
            if (histories != null && histories.size() == MAX_ITME) {
                DBManager.getDBManager().delete(histories.get(histories.size() - 1).getId());
            }
            /**3.插入一條數據**/
            history = new History();
            history.setContent(sv.getInputText());
            history.setTime(new Date().toString());
            long num = DBManager.getDBManager().insert(history);
            if (num != -1) {
                Log.d(Contacts.TAG, "插入成功");
            } else {
                Log.d(Contacts.TAG, "插入失敗");
            }

        }

        notifyAdapter();
    }

    /**
     * 更新數據庫當中的數據
     */
    private void notifyAdapter() {
        histories = DBManager.getDBManager().queryAll();
        commonAdapter.notifyDataSetChanged(histories);
    }
}

五.GitHub

發佈了134 篇原創文章 · 獲贊 73 · 訪問量 63萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章