Sqlite   发布时间:2022-05-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Using your own SQLite database in Android applications大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

@H_919_1@most all of the AndroID examples and tutorials out there assume you want to create and populate your database at runtime and not to use and access an independent,preloaded database with your AndroID application.

The method I'm going to show you takes your own sqlite database file from the "assets" folder and copIEs into the system database path of your application so the sqliteDatabase API can open and access it normally.

1. Preparing the sqlite database file.

Assuming you already have your sqlite database created,we need to do some modifications to it.
If you don't have a sqlite manager I recommend you to download the opensource
sqlite Database Browser available for Win/linux/Mac.

Open your database and add a new table called "androID_Metadata",you can execute the following sql statement to do it:

CREATEtable"androID_Metadata" ("locale" TEXTDEFAulT'en_US')

Now insert a single row with the text 'en_US' in the "androID_Metadata" table:

INSERTINTO"androID_Metadata" VALUES('en_US')

Then,it is necessary to rename the priMary ID fIEld of your tables to "_ID" so AndroID will kNow where to bind the ID fIEld of your tables.
You can easily do this with
sqlite Database Browser by pressing the edit table button,then SELEcTing the table you want to edit and finally SELEcTing the fIEld you want to rename.

After renaming the ID fIEld of all your data tables to "_ID" and adding the "androID_Metadata" table,your database it's ready to be used in your AndroID application.

@H_919_1@modifIEd database

Note: in this image we see the tables "CategorIEs" and "Content" with the ID fIEld renamed to "_ID" and the just added table "androID_Metadata".

2. copying,opening and accessing your database in your AndroID application.

Now just put your database file in the "assets" folder of your project and create a Database Helper class by extending thesqliteOpenHelper class from the "androID.database.sqlite" package.

@H_919_1@make your DataBaseHelper class look like this:

package com.test;

import java.io.fiLeoutputStream;
import java.io.IOException;
import java.io.inputStream;
import java.io.outputStream;

import androID.content.Context;
import androID.database.sqlException;
import androID.database.sqlite.sqliteDatabase;
import androID.database.sqlite.sqliteException;
import androID.database.sqlite.sqliteOpenHelper;

public class DataBaseHelper extends sqliteOpenHelper {
	// The AndroID's default system path of your application database.
	private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
	private static String db_name = "myDBname.db";
	private sqliteDatabase myDataBase;
	private final Context myContext;

	/**
	 * * Constructor * Takes and keeps a reference of the passed context in
	 * order to access to the application assets and resources. * @param context
	 */
	public DataBaseHelper(Context context) {
		super(context,db_name,null,1);
		this.myContext = context;
	}

	/**
	 * * Creates a empty database on the system and rewrites it with your own
	 * database. *
	 */
	public voID createDataBase() throws IOException {
		Boolean dbExist = checkDataBase();
		sqliteDatabase db_Read = null; 		if (dbExist) {
			// do nothing - database already exist
		}

		else {
			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			db_Read = this.getReadableDatabase(); db_Read.close(); 			try {
				copyDataBase();
			} catch (IOException E) {
				throw new Error("Error copying database");
			}
		}
	}

	/**
	 * * check if the database already exist to avoID re-copying the file each
	 * time you open the application. * @return true if it exists,false if it
	 * doesn't
	 */
	private Boolean checkDataBase() {
		sqliteDatabase checkDB = null;
		try {
			String myPath = DB_PATH + db_name;
			checkDB = sqliteDatabase.openDatabase(myPath,sqliteDatabase.oPEN_Readonly);
		} catch (sqliteException E) {
			// database does't exist yet.
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}

	/**
	 * * copIEs your database from your local assets-folder to the just created
	 * empty database in the * system folder,from where it can be accessed and
	 * handled. * This is done by transfering bytestream. *
	 */

	private voID copyDataBase() throws IOException {
		// Open your local db as the input stream
		inputStream myinput = myContext.getAssets().open(db_name);
		// Path to the just created empty db
		String outfilename = DB_PATH + db_name;
		// Open the empty db as the output stream
		OutputStream myOutput = new fiLeoutputStream(outfileName);
		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myinput.read(buffer)) > 0) {
			myOutput.write(buffer,length);
		}
		// Close the streams
		myOutput.flush();
		myOutput.close();
		myinput.close();
	}

	public voID openDataBase() throws sqlException {
		// Open the database
		String myPath = DB_PATH + db_name;
		myDataBase = sqliteDatabase.openDatabase(myPath,sqliteDatabase.oPEN_Readonly);
	}

	@OverrIDe
	public synchronized voID close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}

	@OverrIDe
	public voID onCreate(sqliteDatabase db) {
	}

	@OverrIDe
	public voID onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
	}

	// Add your public Helper methods to access and get content from the
	// database.
	// You Could return cursors by doing "return myDataBase.query(....)" so it'd
	// be easy
	// to you to create adapters for your vIEws.


}

That's it.
Now you can create a new instance of this DataBaseHelper class and call the createDataBase() and openDataBase() methods. Remember to change the "YOUR_PACKAGE" to your application package namespace (i.e: com.examplename.myapp) in the DB_PATH String.

DataBaseHelper myDbHelper = new DataBaseHelper();
		myDbHelper = new DataBaseHelper(this);
		try {
			myDbHelper.createDataBase();
		} catch (IOException ioE) {
			throw new Error("Unable to create database");
		}
		try {
			myDbHelper.openDataBase();
		} catch (sqlException sqlE) {
			throw sqle;
		}


之前没有加入这两行,在某些手机上会报如下错误:

会找不到某张表,但是,你查看数据库,发现有这张表。

大佬总结

以上是大佬教程为你收集整理的Using your own SQLite database in Android applications全部内容,希望文章能够帮你解决Using your own SQLite database in Android applications所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: