文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android在Sqlite3中的应用及多线程使用数据库的建议(实例代码)

2024-04-02 19:55

关注

1、首先先建立一个DatabaseHelper类,继承自SQLiteOpenHelper,用于建立数据库,并可更新数据库例如我新建了两张表

public class DatabaseHelper extends SQLiteOpenHelper {

    private static DatabaseHelper _databaseHelper;
    private static final String TAG = DatabaseHelper.class.getSimpleName();
    public synchronized static DatabaseHelper getInstance(Context context)
    {
        if(_databaseHelper==null)
        {
            _databaseHelper = new DatabaseHelper(context,"cgjlb",null,2);
        }
        return _databaseHelper;
    }
    public synchronized static void destoryInstance(){
        if(_databaseHelper!=null){
            _databaseHelper=null;
    public DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //主表记录
        String sql = "create table t_share(_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real)";
        sqLiteDatabase.execSQL(sql);
        //记录历史表
        sql = "create table t_sharehis(_id integer primary key autoincrement,shareid integer, shareprice real,uptime text)";
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        Log.d(TAG, "onUpgrade: upddatabase");
        sqLiteDatabase.execSQL("drop table t_share");
        sqLiteDatabase.execSQL("drop table t_sharehis");
        onCreate(sqLiteDatabase);
}

2、编写数据库具体操作类、增删改查我都写了

public class ShareDbService {

    SQLiteDatabase db = null;
    DatabaseHelper databaseHelper;
    private static final String TAG = ShareDbService.class.getSimpleName();
    public ShareDbService(Context context) {
        databaseHelper = DatabaseHelper.getInstance(context);
        db = databaseHelper.getWritableDatabase();
    }
    public void addShareInfo(ShareBean shareBean)
    {
        int Id = getShareId(shareBean.getShareNum());
        if(Id==-1) {
            ContentValues values = new ContentValues();
            values.put("sharenum", shareBean.getShareNum());
            values.put("sharename", shareBean.getShareName());
            values.put("shareprice", shareBean.getSharePrice());
            values.put("sharelastprice", shareBean.getShareLastPrice());
            values.put("uptime", shareBean.getUptime());
            values.put("addtime",shareBean.getAddtime());
            double shareprice = shareBean.getSharePrice();
            double sharelastprice = shareBean.getShareLastPrice();
            double bl = (sharelastprice-shareprice)/shareprice*100;
            values.put("bl", new DecimalFormat("0.00").format(bl));
            db = databaseHelper.getWritableDatabase();
            db.insert("t_share", null, values);
            ShareHisBean shareHisBean = new ShareHisBean();
            shareHisBean.setShareId(getShareId(shareBean.getShareNum()));
            shareHisBean.setSharePrice(shareBean.getSharePrice());
            shareHisBean.setUpTime(shareBean.getUptime());
            addShareHis(shareHisBean);
            db.close();
        }
    private void addShareHis(ShareHisBean shareHisBean){
        ContentValues values = new ContentValues();
        values.put("shareid", shareHisBean.getShareId());
        values.put("shareprice", shareHisBean.getSharePrice());
        values.put("uptime", shareHisBean.getUptime());
        db.insert("t_sharehis", null, values);
        db.close();
    public void refreshShare(ShareHisBean shareHisBean,double sharePrice){
        try {
            //更新信息主表
            values.put("uptime", shareHisBean.getUptime());
            values.put("sharelastprice", shareHisBean.getSharePrice());
            String[] args = {String.valueOf(shareHisBean.getShareId())};
            double sharelastprice = shareHisBean.getSharePrice();
            double bl = (sharelastprice - sharePrice) / sharePrice * 100;
            values.put("bl", bl);
            db.update("t_share", values, "_Id=?", new String[]{String.valueOf(shareHisBean.getShareId())});
            //添加记录
            values = new ContentValues();
            values.put("shareid", shareHisBean.getShareId());
            values.put("shareprice", shareHisBean.getSharePrice());
            db.insert("t_sharehis", null, values);
        }catch(Exception ex){
            ex.printStackTrace();
        finally {
    public void delShare(String Id){
        db.delete("t_share","_Id=?",new String[]{Id});
        db.delete("t_sharehis","shareid=?",new String[]{Id});
    private int getShareId(String shareNum) {
        db = databaseHelper.getReadableDatabase();
        String sql = "select _Id from t_share where sharenum='" + shareNum + "'";
        int Id = -1;
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.moveToNext()){
                Id = cursor.getInt(0);
            }
        cursor.close();
        return Id;
    public List<ShareBean> getShareList(){
        List<ShareBean> shareBeans = new ArrayList<>();
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,uptime,addtime,bl from t_share order by _Id desc";
                ShareBean shareBean = new ShareBean();
                shareBean.set_Id(cursor.getInt(0));
                shareBean.setShareNum(cursor.getString(1));
                shareBean.setShareName(cursor.getString(2));
                shareBean.setSharePrice(cursor.getDouble(3));
                shareBean.setShareLastPrice(cursor.getDouble(4));
                shareBean.setUptime(cursor.getString(5));
                shareBean.setAddtime(cursor.getString(6));
                shareBean.setBl(cursor.getDouble(7));
                shareBeans.add(shareBean);
        return shareBeans;
    public List<ShareHisBean> getShareListHis(int ShareId){
        List<ShareHisBean> shareHisBeans = new ArrayList<>();
        String sql = "select _id,shareid,shareprice,uptime from t_sharehis where shareid='"+String.valueOf(ShareId)+"' order by _id desc";
                ShareHisBean shareHisBean = new ShareHisBean();
                shareHisBean.set_Id(cursor.getInt(0));
                shareHisBean.setShareId(cursor.getInt(1));
                shareHisBean.setSharePrice(cursor.getDouble(2));
                shareHisBean.setUpTime(cursor.getString(3));
                shareHisBeans.add(shareHisBean);
        return shareHisBeans;
    public ShareBean getShareInfo(int ShareId) {
        ShareBean shareBean = new ShareBean();
        //_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,addtime,uptime,bl from t_share where _Id='"+String.valueOf(ShareId)+"'";
            if (cursor.moveToNext()){
                shareBean.setAddtime(cursor.getString(5));
                shareBean.setUptime(cursor.getString(6));
        return shareBean;
}

3、实际中的应用,就举一个例子吧,数据库操作不用开新线程,直接在主线程里弄就行

ShareDbService shareDbService = new ShareDbService(getContext());
 shareDbService.delShare(String.valueOf(shareBean.get_Id()));

4、需要注意的是SQLite不支持多线程,最好是能批量修改,否则很麻烦,如果一定要多线程 ,比如循环请求网络更新数据库时,可以使用CountDownLatch,先将数据弄在一个集合里,等子线程全部执行完成后,再更新数据库。此方法具体应用如下

先声明一个变量

CountDownLatch latch;

实际应用代码

//设置多线程 个数,一共用多少个线程一定要写清楚,后面是要减的。
        latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {            
            new Thread(()-> {
                try {
                    //网络请求等操作
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //这里会自动减1操作,一定要写。
                    latch.countDown();
                }
            }).start();
        };
        try {
            latch.await();
           //最后执行主程序,比如更新数据库
            Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

到此这篇关于Android在Sqlite3中的应用及多线程使用数据库的建议的文章就介绍到这了,更多相关android Sqlite3多线程内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯