Android context provider DB更新

2024-05-28 06:38

本文主要是介绍Android context provider DB更新,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

實際測試
new MyDBHlper時,會自動判斷,帶入的 version是不是跟之前的一樣,如果不一樣,就會先執行 MyDBHlper的onUpgrade

執行順序為

MyContentProvider: onCreate: 
MyDBHlper: onUpgrade: oldVersion:1newVersion:2
MyDBHlper: onCreate:

复制代码
public class MyContentProvider extends ContentProvider {@Overridepublic boolean onCreate() {Log.d(Tag, "onCreate: ");// MyDBHlper dbHper = new MyDBHlper(getContext(), DBname, null, 1);//FIXME:test version changeMyDBHlper dbHper = new MyDBHlper(getContext(), DBname, null, 2);MyDB = dbHper.getWritableDatabase();return true;}
}public class MyDBHlper extends SQLiteOpenHelper {@Overridepublic void onCreate(SQLiteDatabase db) {Log.d(Tag, "onCreate: ");db.execSQL(crTBsql);db.execSQL(initDBDate);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Log.d(Tag, "onUpgrade: oldVersion:" + oldVersion + "newVersion:" + newVersion);db.execSQL("DROP TABLE IF EXISTS " + TBname);onCreate(db);}
}
复制代码

 

***************************************************************************************************

 

轉載自http://mrraybox.blogspot.tw/2017/01/android-sqlite-onupgrade.html

 

本篇主要是示範:
1. 說明onUpgrade何時會啟用。
2. 示範如何使用onUpgrade。
3. 觀察onUpgrade使用後的前後差異。

相信開始接觸SQLite的大家都知道SQLiteOpenHelper中有一個方法叫onUpgrade,但是這個方法是做什麼用的呢?首先我們知道onCreate是在Android載入時,找不到對應的資料庫資料,就會觸發的一個方法。而onUpgrade呢,則是在資料庫的結構有所改變時,才會觸發的一個方法。

舉例來說,假如我在一月時,寫了一個App給其他人使用,在二月時,因改版需求,所以需要新增或刪減資料表的欄位。但是此時,那些使用我們所寫的App的用戶們,在這段期間已經儲存許多資料了。為了保存用戶舊的資料,此時我們就需要運用到onUpgrade來修改我們資料表的結構。

首先這裡示範我們一開始所寫的App。首先Layout部分的配置。
File Name:activity_main.xml

复制代码
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><Buttonandroid:id="@+id/btn_new"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="新增" /><Buttonandroid:id="@+id/btn_delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="刪除" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="right"android:orientation="horizontal" ><EditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="ID"android:id="@+id/edt1"android:layout_weight="1" /><EditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="Row1"android:id="@+id/edt2"android:layout_weight="1" /><EditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="Row2"android:id="@+id/edt3"android:layout_weight="1" /><Buttonandroid:id="@+id/btn_alter"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="修改" /></LinearLayout><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="txt"android:id="@+id/txt"/></LinearLayout></ScrollView>
复制代码

File Name:MainActivity

复制代码
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button btnNew, btnDel, btnAlt;private EditText edtID, edtRow1, edtRow2;private TextView txt;private MyHelper helper;private SQLiteDatabase db;private Cursor c;private String result;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnNew = (Button) this.findViewById(R.id.btn_new);btnDel = (Button) this.findViewById(R.id.btn_delete); btnAlt = (Button) this.findViewById(R.id.btn_alter);edtID = (EditText) this.findViewById(R.id.edt1);edtRow1 = (EditText) this.findViewById(R.id.edt2);edtRow2 = (EditText) this.findViewById(R.id.edt3);txt = (TextView) this.findViewById(R.id.txt);btnNew.setOnClickListener(this);btnDel.setOnClickListener(this);btnAlt.setOnClickListener(this);helper = new MyHelper(this, "dbname", null, 1);db = helper.getWritableDatabase();queryDB();}private void queryDB() {c = db.query("tablename", null, null, null, null, null, null);result="";for(int i=0; i<c.getColumnCount();i++){result+=c.getColumnName(i)+", ";}result+="\n";while (c.moveToNext()) {result += c.getString(c.getColumnIndex("_id")) + ", "+c.getString(c.getColumnIndex("row1")) + ", "+c.getString(c.getColumnIndex("row2")) +"\n";}txt.setText(result);}@Overridepublic void onClick(View view) {String id = edtID.getText().toString();ContentValues values = new ContentValues();switch (view.getId()){case R.id.btn_new:values.put("row1", "Row1");values.put("row2", "Row2");db.insert("tablename", null, values);queryDB();break;case R.id.btn_delete:db.delete("tablename", "_id="+id,null);queryDB();break;case R.id.btn_alter:String row1 = edtRow1.getText().toString();String row2 = edtRow2.getText().toString();values.put("row1", row1);values.put("row2", row2);db.update("tablename", values, "_id=" + id, null);queryDB();break;}}@Overridepublic void finish() {c.close();db.close();super.finish();}
}    
复制代码

File Name:MyHelper

复制代码
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;public class MyHelper extends SQLiteOpenHelper {private String createTab;private String tableName = "tablename";public MyHelper(Context context, String db_name, SQLiteDatabase.CursorFactory factory, int db_version) {super(context, db_name, factory, db_version);}@Overridepublic void onCreate(SQLiteDatabase db) {createTab = "create table "+ tableName +" (_id integer primary key AUTOINCREMENT, row1 text, row2 text)";db.execSQL(createTab);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
复制代码

在用戶新增完資料後,就會變成下面這樣。

接著是我們改版後的程式碼。 
File Name:MainActivity
复制代码
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button btnNew, btnDel, btnAlt;private EditText edtID, edtRow1, edtRow2;private TextView txt;private MyHelper helper;private SQLiteDatabase db;private Cursor c;private String result;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnNew = (Button) this.findViewById(R.id.btn_new);btnDel = (Button) this.findViewById(R.id.btn_delete);btnAlt = (Button) this.findViewById(R.id.btn_alter);edtID = (EditText) this.findViewById(R.id.edt1);edtRow1 = (EditText) this.findViewById(R.id.edt2);edtRow2 = (EditText) this.findViewById(R.id.edt3);txt = (TextView) this.findViewById(R.id.txt);btnNew.setOnClickListener(this);btnDel.setOnClickListener(this);btnAlt.setOnClickListener(this);helper = new MyHelper(this, "dbname", null, 2);db = helper.getWritableDatabase();queryDB();}private void queryDB() {c = db.query("tablename", null, null, null, null, null, null);result="";for(int i=0; i<c.getColumnCount();i++){result+=c.getColumnName(i)+", ";}result+="\n";while (c.moveToNext()) {result += c.getString(c.getColumnIndex("_id")) + ", "+c.getString(c.getColumnIndex("row1")) + ", "+c.getString(c.getColumnIndex("row2")) +"\n";}txt.setText(result);}@Overridepublic void onClick(View view) {String id = edtID.getText().toString();ContentValues values = new ContentValues();switch (view.getId()){case R.id.btn_new:values.put("row1", "Row1");values.put("row2", "Row2");db.insert("tablename", null, values);queryDB();break;case R.id.btn_delete:db.delete("tablename", "_id="+id,null);queryDB();break;case R.id.btn_alter:String row1 = edtRow1.getText().toString();String row2 = edtRow2.getText().toString();values.put("row1", row1);values.put("row2", row2);db.update("tablename", values, "_id=" + id, null);queryDB();break;}}@Overridepublic void finish() {c.close();db.close();super.finish();}
}
复制代码

File Name:MyHelper

复制代码
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;public class MyHelper extends SQLiteOpenHelper {private String createTab;private String tableName = "tablename";public MyHelper(Context context, String db_name, SQLiteDatabase.CursorFactory factory, int db_version) {super(context, db_name, factory, db_version);}@Overridepublic void onCreate(SQLiteDatabase db) {   createTab = "create table "+ tableName +" (_id integer primary key AUTOINCREMENT, row1 text, row2 text, row3 text)";db.execSQL(createTab);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {if(oldVersion == 1 && newVersion == 2){//Adding a row3String sql = "alter table "+ tableName +" add row3 text";db.execSQL(sql);}}
}
复制代码

實作後,則會變成下面這樣。有發現差異在哪嗎?


改版後的App不但保存了用戶的舊資料,同時還新增了一個row3的欄位,是不是很方便的一個功能呀!

这篇关于Android context provider DB更新的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1009817

相关文章

SQL Server 中的表进行行转列场景示例

《SQLServer中的表进行行转列场景示例》本文详细介绍了SQLServer行转列(Pivot)的三种常用写法,包括固定列名、条件聚合和动态列名,文章还提供了实际示例、动态列数处理、性能优化建议... 目录一、常见场景示例二、写法 1:PIVOT(固定列名)三、写法 2:条件聚合(CASE WHEN)四、

Mybatis对MySQL if 函数的不支持问题解读

《Mybatis对MySQLif函数的不支持问题解读》接手项目后,为了实现多租户功能,引入了Mybatis-plus,发现之前运行正常的SQL语句报错,原因是Mybatis不支持MySQL的if函... 目录MyBATis对mysql if 函数的不支持问题描述经过查询网上搜索资料找到原因解决方案总结Myb

Nginx更新SSL证书的实现步骤

《Nginx更新SSL证书的实现步骤》本文主要介绍了Nginx更新SSL证书的实现步骤,包括下载新证书、备份旧证书、配置新证书、验证配置及遇到问题时的解决方法,感兴趣的了解一下... 目录1 下载最新的SSL证书文件2 备份旧的SSL证书文件3 配置新证书4 验证配置5 遇到的http://www.cppc

MySQL 筛选条件放 ON后 vs 放 WHERE 后的区别解析

《MySQL筛选条件放ON后vs放WHERE后的区别解析》文章解释了在MySQL中,将筛选条件放在ON和WHERE中的区别,文章通过几个场景说明了ON和WHERE的区别,并总结了ON用于关... 今天我们来讲讲数据库筛选条件放 ON 后和放 WHERE 后的区别。ON 决定如何 "连接" 表,WHERE

mysql_mcp_server部署及应用实践案例

《mysql_mcp_server部署及应用实践案例》文章介绍了在CentOS7.5环境下部署MySQL_mcp_server的步骤,包括服务安装、配置和启动,还提供了一个基于Dify工作流的应用案例... 目录mysql_mcp_server部署及应用案例1. 服务安装1.1. 下载源码1.2. 创建独立

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

MySQL日志UndoLog的作用

《MySQL日志UndoLog的作用》UndoLog是InnoDB用于事务回滚和MVCC的重要机制,本文主要介绍了MySQL日志UndoLog的作用,文中介绍的非常详细,对大家的学习或者工作具有一定的... 目录一、Undo Log 的作用二、Undo Log 的分类三、Undo Log 的存储四、Undo

MySQL游标和触发器的操作流程

《MySQL游标和触发器的操作流程》本文介绍了MySQL中的游标和触发器的使用方法,游标可以对查询结果集进行逐行处理,而触发器则可以在数据表发生更改时自动执行预定义的操作,感兴趣的朋友跟随小编一起看看... 目录游标游标的操作流程1. 定义游标2.打开游标3.利用游标检索数据4.关闭游标例题触发器触发器的基

MySQL查看表的历史SQL的几种实现方法

《MySQL查看表的历史SQL的几种实现方法》:本文主要介绍多种查看MySQL表历史SQL的方法,包括通用查询日志、慢查询日志、performance_schema、binlog、第三方工具等,并... 目录mysql 查看某张表的历史SQL1.查看MySQL通用查询日志(需提前开启)2.查看慢查询日志3.

MySQL底层文件的查看和修改方法

《MySQL底层文件的查看和修改方法》MySQL底层文件分为文本类(可安全查看/修改)和二进制类(禁止手动操作),以下按「查看方法、修改方法、风险管控三部分详细说明,所有操作均以Linux环境为例,需... 目录引言一、mysql 底层文件的查看方法1. 先定位核心文件路径(基础前提)2. 文本类文件(可直