在Android的onUpgrade()SQLite数据库数据库、Android、onUpgrade、SQLite

2023-09-05 02:19:35 作者:忘不掉,却又假装记不起〃

我创建了一个Android应用程序,检查在启动时是否有应用程序的新版本。如果是的话,应用程序下载新的apk文件,并在安装新的APK。 我的应用程序使用SQLite数据库。但这个数据库,从一个版本到其他可以改变。 我想我必须使用的方法:

I created an Android application which, check at startup if there is a new version of application. If yes, the application download the new apk file and over-install new apk. My application use the sqlite db. But this db, from one version to other can change. I think I have to use the method:

 onUpgrade()

但我不知道如何使用它。

but I don't know exactly how to use it.

当我开始我用这个code克里特数据库(如果不存在)的应用程序:

When I start the application I use this code for crete database(if not exists):

DbHelper mDHelper = new DbHelper(context, DB_NAME, null, DB_VERSION)

我应该怎么改变,如果我想使用 onUpgrade()的方法? 而且做的时候我一定要打电话了吗?

What should I change if I want use onUpgrade() method? And when do I have to call it?

推荐答案

onUpgrade()被称为(你不把它自己),当版本的数据库中改变它是指基本表结构的改变等。

onUpgrade() is called (you do not call it yourself) when version of your DB changed which means underlying table structure changed etc.

在一般这意味着操作系统是告诉你的哎,你自找的数据库结构的版本10,但我发现,我们得到的东西旧的在这里,所以这是你的机会来解决你开始使用数据库之前(和潜在的死机是由于结构不匹配)的。

In general it means that OS is telling you "hey, you asked for database structure version 10 but I found we got something older here, so this is you chance to fix that before you start using database (and potentially crash due to structure mismatch)".

在该方法中,你应该做的一切,是必要的,以及..升级您的旧数据​​库结构匹配,如添加/滴速列,将行的内容,甚至丢弃旧的数据库,并完全从头开始创建它目前的版本要求结构 - 为Android没关系你做什么,在这里 - 它只是一个为你的code做必要的工作(如果有的话)排序紧急回调。你需要知道的用户,所以你必须始终从版本X到Y明知是X升级可能不等于IE浏览器(Y-1)可能不经常更新。

In that method you should do all that is necessary to, well.. upgrade structure of your old database to structure matching current version requirements like adding/droping columns, converting row contents or even dropping old db completely and create it from scratch - for Android it does not matter what you do here - it's just a sort of emergency callback for your code to do the necessary job (if any). You need to be aware that users may not update frequently so you have to always handle upgrade from version X to Y knowing that X may not be equal to i.e. (Y-1).