Android 本地数据库实现历史记录功能

恩,历史记录实现可以采取网络请求的形式,这样比较耗时;对于存储在本地的方法,我常用的是ShaerdPreferences和数据库;这次主要是通过本地数据库来实现历史记录。

 

首先要建表,创建需要存储的字段名,为了每次将选中的历史记录置顶,我增加了时间字段

​
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DbHelper extends SQLiteOpenHelper {

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

    
    @Override
    public void onCreate(SQLiteDatabase db) {
        //建表(名称记录):自增长的主键,名称,最后一次更新时间
        db.execSQL("create table history(_id integer primary key autoincrement, name varchar(20) , lasttime varchar(50));");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

    }
}

​
HistoryDao
​
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.SystemClock;

import java.util.ArrayList;
import java.util.List;


public class HistoryDao {

    //创建数据库
    private DbHelper dbHelper;

    private String tabHistory = "history";

    private HistoryDao(Context context) {
        dbHelper = new DbHelper(context, "history.db", null, 1);
    }

    private static HistoryDao instance;

    public static synchronized HistoryDao getInstance(Context context) {
        if (instance == null) {
            instance = new HistoryDao(context);
        }
        return instance;
    }

    /**
     * 增加历史记录
     */
    public void addHistory(String name) {
        //获得一个可写的数据库的一个引用
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("lasttime", CommUtil.getCurrentDate());// KEY 是列名,vlaue 是该列的值
        if (getIdByName(name)==0) {
            values.put("name", name);

            db.insert(tabHistory, null, values);
        } else {
            db.update(tabHistory,values,"name = ?", new String[]{name});
        }

    }

   
    /**
     * 删除历史记录
     */
    public void delHistory(int _id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //表名  删除的条件
        db.delete(tabHistory, "_id = "+_id,null);
    }

    /**
     * 删除全部历史记录
     */
    public void delAllHistory(List beans) {
        for (int i=0;i getHistoryData() {
        //创建集合对象
        List data = new ArrayList();

        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = db.rawQuery("select * from history order by lasttime desc;", null);
        // 返回的 cursor 默认是在第一行的上一行
        //遍历
        while (cursor.moveToNext()) {// cursor.moveToNext() 向下移动一行,如果有内容,返回true
            int id=cursor.getInt(0);
            String name = cursor.getString(cursor.getColumnIndex("name"));

            HisNameBean bean = new HisNameBean(id, name);
            //封装的对象添加到集合中
            data.add(bean);
        }

        //关闭cursor
        cursor.close();
        SystemClock.sleep(1000);// 休眠2秒,数据比较多,比较耗时的情况
        return data;

    }

    ;

    /**
     * 获得历史记录数量
     */
    public int getHistoryCount() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(tabHistory, new String[]{"count(*)"}, null, null, null, null, null);

        cursor.moveToNext();
        int count = cursor.getInt(0);// 仅查了一列,count(*) 这一刻列

        cursor.close();

        return count;

    }

    /**
     * 根据名称获得_ID
     */
    public int getIdByName(String name) {

        int id = 0;
        //获得一个可读的数据库的一个引用
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        //查询  表   列   条件
        Cursor cursor = db.query(tabHistory, null, "name = ?", new String[]{name}, null, null, null);

        if (cursor.moveToNext()) {// 如果查到了,移动成功
            id = cursor.getInt(0);

        }

        cursor.close();
        return id;
    }

}

​

表history的基类

public class HisNameBean {

    private int id;
    private String name;

    public HisNameBean (int id, String name ) {
        this.id=id;
        this.name = name ;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

在Activity中使用

private HistoryDao historyDao;
List beans = new ArrayList<>();
private NameHisAdapter adapter;

初始化: 

historyDao = HistoryDao.getInstance(this);

 

 /**
     * 初始化历史记录
     */
    private void initHistoryData() {

        new Thread() {
            public void run() {
                if (beans == null) {
                    beans = historyDao.getHistoryData();
                } else {
                    beans .clear();
                    beans .addAll(historyDao.getHistoryData());
                }
                
                // handler.sendEmptyMessage(100);
                Message msg = Message.obtain();
                msg.what = 100;
                handler.sendMessage(msg);
            }
        }.start();

        tvClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 全部清除
                historyDao.delAllHistory(busBeans);
            }
        });
    }



 //使用Handler更新主线程(UI线程)
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100://子线程获得了数据,开始刷新页面
                    if (beans.size() == 0) {
                        // 没有历史记录的情况

                    } else {
                        if (adapter == null) { //第一次加载
                            LinearLayoutManager layoutmanager = new LinearLayoutManager(Activity.this);
                            //设置RecyclerView 布局
                            rvHistory.setLayoutManager(layoutmanager);
                            adapter = new NameHisAdapter(Activity.this, beans);
                            rvHistory.setAdapter(adapter);
                            adapter.setOnDelClickListener(new NameHisAdapter.OnDelClickListener() {
                                @Override
                                public void onDelClick(View view, int position, int count) {
                                    // 删除当前历史记录     historyDao.delHistory(historyDao.getIDByName(beans.get(position).getName().toString().trim()));
                                    beans.remove(position);
                                    adapter.notifyDataSetChanged();
                                    
                                }
                            });
                            adapter.setOnItemClickListener(new NameHisAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    // 获得对应名称
                                  String name= beans.get(position).getName();

                                        // 添加历史记录
                                        historyDao.addHistory(beans.get(position).getName());

                      
                                }
                            });
                        } else {
                            //追加数据
                            adapter.notifyDataSetChanged();// 刷新listView 否则仍会从头开始 显示
                        }
                        llData.setVisibility(View.VISIBLE);
                        vNodata.setVisibility(View.GONE);
                    }
                    break;
            }
        }

    };

根据实际情况进行增删改查操作

你可能感兴趣的:(数据存储,Android,SQLite,本地数据库,历史记录)