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

相关文章

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

MySQL中的锁机制详解之全局锁,表级锁,行级锁

《MySQL中的锁机制详解之全局锁,表级锁,行级锁》MySQL锁机制通过全局、表级、行级锁控制并发,保障数据一致性与隔离性,全局锁适用于全库备份,表级锁适合读多写少场景,行级锁(InnoDB)实现高并... 目录一、锁机制基础:从并发问题到锁分类1.1 并发访问的三大问题1.2 锁的核心作用1.3 锁粒度分