android:从资产导出数据';s文件夹(sqllite db)并将其导入app';s数据库
更新android:从资产导出数据';s文件夹(sqllite db)并将其导入app';s数据库,android,eclipse,sqlite,Android,Eclipse,Sqlite,更新 import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import androi
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase db1;
// Static Final Variable database meta information
static final String DATABASE = "assesmenttool.db";
static final int DATABASE_VERSION = 1;
//Table Student Details
static final String TABLEStudent = "StudentDetails";
static final String S_ID = "_id";
static final String SchoolID = "SchoolID";
static final String SchoolName = "schoolname";
static final String StudentFirstName = "StudentFirstName";
static final String StudentLastName ="StudentLastName";
static final String StudentClassLevel ="StudentClassLevel";
static final String RollNo="RollNo";
static final String TestDate ="TestDate";
//Table Response Details
static final String TABLEResponse = "TableResponse";
static final String R_ID = "_id";
static final String StudentID = "StudentID";
static final String R_QuestionID = "QuestionID";
static final String QuestOptionID = "QuestOptionID";
//Table Question Master
static final String TableQuestionMaster = "TableQuestionMaster";
static final String Q_ID= "_id";
static final String Module_ID = "Module_ID";
static final String SubModule_ID = "SubModule_ID";
static final String SubModuleQuestion_ID ="SubModuleQuestion_ID";
static final String Question_ID= "Question_ID";
static final String Title = "Title";
static final String Module = "Module";
static final String TitleDescription = "TitleDescription";
static final String QuestionText = "QuestionText";
static final String QuestionImage = "QuestionImage";
static final String QuestionTemplate = "QuestionTemplate";
static final String CorrectOptionID = "CorrectOptionID";
//Table Template Master
static final String TableTemplateMaster = "TemplateMaster";
static final String T_ID= "_id";
static final String Template_ID= "Template_ID";
static final String Name = "Name";
static final String Description = "Description";
//Table Question Option
static final String TableQuestionOption = "TableQuestionOption";
static final String TQP_ID= "_id";
static final String TQP_QuestionID = "QuestionID";
static final String TQP_OptionID = "TQP_OptionID";
static final String OptionText = "OptionText";
//Table Class Master
static final String TableClassMaster = "TableClassMaster";
static final String Class_ID= "_id";
static final String Class = "class";
private static String DB_PATH = "/data/data/com.cldonline.assesmenttool/databases/";
private static String DB_NAME = "assesmenttool.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 DBHelper(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();
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.
this.getReadableDatabase();
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, null, 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, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// Override onCreate method
@Override
public void onCreate(SQLiteDatabase db) {
}
public List<String> getAllClasses(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableClassMaster;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> getAllOptions(String Qid){
List<String> options = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableQuestionOption +" "+"where QuestionID ='"+Qid+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
options.add(cursor.getString(2));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return options;
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<Cursor> getData(String Query){
//get writable database
SQLiteDatabase sqlDB = this.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add(null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0) {
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
} catch(SQLException sqlEx){
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
} catch(Exception ex){
Log.d("printing exception", ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
}
我找到了这个链接
有人能解释一下我将如何使用这个函数编写更新/插入语句吗
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu强
问题
我正在尝试创建一种方法,可以将存储在sqllite数据库中的数据复制到我的应用程序的数据库中。结构相似。我只是不想一行一行地插入
我正在寻找一种方法,通过这种方法,我可以将存储在资产文件夹或外部存储器中的预输入数据复制到我的应用数据库中
我在应用程序中填充数据时遇到问题。我不想为每一行和每一列编程编写5000条insert语句
有人能提出一个方法吗。我是android新手,请详细解释或提供链接
我的DB助手类
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase db1;
// Static Final Variable database meta information
static final String DATABASE = "assesmenttool.db";
static final int DATABASE_VERSION = 1;
//Table Student Details
static final String TABLEStudent = "StudentDetails";
static final String S_ID = "_id";
static final String SchoolID = "SchoolID";
static final String SchoolName = "schoolname";
static final String StudentFirstName = "StudentFirstName";
static final String StudentLastName ="StudentLastName";
static final String StudentClassLevel ="StudentClassLevel";
static final String RollNo="RollNo";
static final String TestDate ="TestDate";
//Table Response Details
static final String TABLEResponse = "TableResponse";
static final String R_ID = "_id";
static final String StudentID = "StudentID";
static final String R_QuestionID = "QuestionID";
static final String QuestOptionID = "QuestOptionID";
//Table Question Master
static final String TableQuestionMaster = "TableQuestionMaster";
static final String Q_ID= "_id";
static final String Module_ID = "Module_ID";
static final String SubModule_ID = "SubModule_ID";
static final String SubModuleQuestion_ID ="SubModuleQuestion_ID";
static final String Question_ID= "Question_ID";
static final String Title = "Title";
static final String Module = "Module";
static final String TitleDescription = "TitleDescription";
static final String QuestionText = "QuestionText";
static final String QuestionImage = "QuestionImage";
static final String QuestionTemplate = "QuestionTemplate";
static final String CorrectOptionID = "CorrectOptionID";
//Table Template Master
static final String TableTemplateMaster = "TemplateMaster";
static final String T_ID= "_id";
static final String Template_ID= "Template_ID";
static final String Name = "Name";
static final String Description = "Description";
//Table Question Option
static final String TableQuestionOption = "TableQuestionOption";
static final String TQP_ID= "_id";
static final String TQP_QuestionID = "QuestionID";
static final String OptionText = "OptionText";
//Table Class Master
static final String TableClassMaster = "TableClassMaster";
static final String Class_ID= "_id";
static final String Class = "class";
// Override constructor
public DBHelper(Context context) {
super(context, DATABASE, null, DATABASE_VERSION);
}
// Override onCreate method
@Override
public void onCreate(SQLiteDatabase db) {
//Create Table Student Details
db.execSQL("CREATE TABLE " + TABLEStudent + " ( " + S_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + SchoolID + " text, "
+ SchoolName + " text, " + StudentFirstName + " text, " + StudentLastName + " text, " + RollNo + " text," + TestDate + " text," + StudentClassLevel + " text)");
//Create Table Response Details
db.execSQL("CREATE TABLE " + TABLEResponse + " ( " + R_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + StudentID + " text, "
+ R_QuestionID + " text, " + QuestOptionID + " text)");
//Create Table Question Master
db.execSQL("CREATE TABLE " + TableQuestionMaster + " ( " + Q_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Question_ID + " text, " + Module_ID + " text, " + SubModule_ID + " text, " + SubModuleQuestion_ID + " text, " + Title + " text, " + Module + " text,"
+ TitleDescription + " text, " + QuestionText + " text, " + QuestionImage + " text, " + QuestionTemplate + " text," + CorrectOptionID + " text)");
//Create Table Template Master
db.execSQL("CREATE TABLE " + TableTemplateMaster + " ( " + T_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Name + " text, "
+ Description + " text)");
//Create Table Question Option
db.execSQL("CREATE TABLE " + TableQuestionOption + " ( " + TQP_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + TQP_QuestionID + " text, "
+ OptionText + " text)");
//Create Table Class Master
db.execSQL("CREATE TABLE " + TableClassMaster + " ( " + Class_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Class + " text)");
}
public List<String> getAllClasses(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableClassMaster;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop old version table
db.execSQL("Drop table " + TABLEStudent);
db.execSQL("Drop table " + TABLEResponse);
db.execSQL("Drop table " + TableQuestionMaster);
db.execSQL("Drop table " + TableTemplateMaster);
db.execSQL("Drop table " + TableQuestionOption);
db.execSQL("Drop table " + TableClassMaster);
// Create New Version table
onCreate(db);
}
}
我用同样的方法。我有一个用于此的帮助器类:
public class DatabaseImport {
private static final String TAG = "DataAdapter";
private final DataBaseHelper mDbHelper;
public DatabaseImport(Context context) {
Context mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public void createDatabase() {
try {
mDbHelper.createDataBase();
} catch (Exception mIOException) {
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
}
我在DBHelper类中调用它
class DataBaseHelper extends SQLiteOpenHelper {
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/yourpackagename/databases/";
private static final String DB_NAME = "databasename";
private static final String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private final Context mContext;
private SQLiteDatabase mDataBase;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);// 1? its Database Version
if (android.os.Build.VERSION.SDK_INT >= 17) {
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.mContext = context;
}
public void createDataBase() {
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if (!mDataBaseExist) {
this.getReadableDatabase();
this.close();
try {
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getResources().openRawResource(R.raw.kindersporttabelle);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
可以使用普通DataBaseHandler访问和使用数据库:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
//databasename
private static final String DATABASE_NAME = "databasename";
//table names
[...]
//game name column names
[....]
private static Context myContext;
private static DatabaseHandler mInstance = null;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
*/
private DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DatabaseHandler getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseHandler(context.getApplicationContext());
}
myContext = context;
return mInstance;
}
@Override
public void onCreate(SQLiteDatabase db) {
Intent intent = new Intent(myContext, MainActivity.class);
myContext.startActivity(intent);
DatabaseImport mDbHelper = new DatabaseImport(myContext);
try {
mDbHelper.createDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + tablename);
myContext.deleteDatabase(DATABASE_NAME);
onCreate(db);
}
}
您只需要调整正确的类名。这应该行得通。祝你好运 检查。提供位于项目资产文件夹中的数据库路径。您可以在的帮助下复制整个数据库
这将解决我的问题 只需使用sqlliteOPenHelper类的帮助 步骤1 添加copyDataBase()函数 步骤2 像这样在你的主要活动中启动它
helper = new DBHelper(this);
try {
helper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
helper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
您的DBHelper类看起来像
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase db1;
// Static Final Variable database meta information
static final String DATABASE = "assesmenttool.db";
static final int DATABASE_VERSION = 1;
//Table Student Details
static final String TABLEStudent = "StudentDetails";
static final String S_ID = "_id";
static final String SchoolID = "SchoolID";
static final String SchoolName = "schoolname";
static final String StudentFirstName = "StudentFirstName";
static final String StudentLastName ="StudentLastName";
static final String StudentClassLevel ="StudentClassLevel";
static final String RollNo="RollNo";
static final String TestDate ="TestDate";
//Table Response Details
static final String TABLEResponse = "TableResponse";
static final String R_ID = "_id";
static final String StudentID = "StudentID";
static final String R_QuestionID = "QuestionID";
static final String QuestOptionID = "QuestOptionID";
//Table Question Master
static final String TableQuestionMaster = "TableQuestionMaster";
static final String Q_ID= "_id";
static final String Module_ID = "Module_ID";
static final String SubModule_ID = "SubModule_ID";
static final String SubModuleQuestion_ID ="SubModuleQuestion_ID";
static final String Question_ID= "Question_ID";
static final String Title = "Title";
static final String Module = "Module";
static final String TitleDescription = "TitleDescription";
static final String QuestionText = "QuestionText";
static final String QuestionImage = "QuestionImage";
static final String QuestionTemplate = "QuestionTemplate";
static final String CorrectOptionID = "CorrectOptionID";
//Table Template Master
static final String TableTemplateMaster = "TemplateMaster";
static final String T_ID= "_id";
static final String Template_ID= "Template_ID";
static final String Name = "Name";
static final String Description = "Description";
//Table Question Option
static final String TableQuestionOption = "TableQuestionOption";
static final String TQP_ID= "_id";
static final String TQP_QuestionID = "QuestionID";
static final String TQP_OptionID = "TQP_OptionID";
static final String OptionText = "OptionText";
//Table Class Master
static final String TableClassMaster = "TableClassMaster";
static final String Class_ID= "_id";
static final String Class = "class";
private static String DB_PATH = "/data/data/com.cldonline.assesmenttool/databases/";
private static String DB_NAME = "assesmenttool.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 DBHelper(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();
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.
this.getReadableDatabase();
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, null, 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, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// Override onCreate method
@Override
public void onCreate(SQLiteDatabase db) {
}
public List<String> getAllClasses(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableClassMaster;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> getAllOptions(String Qid){
List<String> options = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableQuestionOption +" "+"where QuestionID ='"+Qid+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
options.add(cursor.getString(2));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return options;
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<Cursor> getData(String Query){
//get writable database
SQLiteDatabase sqlDB = this.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add(null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0) {
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
} catch(SQLException sqlEx){
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
} catch(Exception ex){
Log.d("printing exception", ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
}
import java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.List;
导入android.content.Context;
导入android.database.Cursor;
导入android.database.MatrixCursor;
导入android.database.SQLException;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteException;
导入android.database.sqlite.SQLiteOpenHelper;
导入android.util.Log;
公共类DBHelper扩展了SQLiteOpenHelper{
公共数据库db1;
//静态最终变量数据库元信息
静态最终字符串DATABASE=“assessmenttool.db”;
静态最终int数据库_版本=1;
//表1学生详细信息
静态最终字符串TABLEStudent=“StudentDetails”;
静态最终字符串S_ID=“_ID”;
静态最终字符串SchoolID=“SchoolID”;
静态最终字符串SchoolName=“SchoolName”;
静态最终字符串StudentFirstName=“StudentFirstName”;
静态最终字符串StudentLastName=“StudentLastName”;
静态最终字符串StudentClassLevel=“StudentClassLevel”;
静态最终字符串RollNo=“RollNo”;
静态最终字符串TestDate=“TestDate”;
//表1响应详细信息
静态最终字符串TABLEResponse=“TABLEResponse”;
静态最终字符串R_ID=“_ID”;
静态最终字符串StudentID=“StudentID”;
静态最终字符串R\u QuestionID=“QuestionID”;
静态最终字符串QuestOptionID=“QuestOptionID”;
//表格问题母版
静态最终字符串TableQuestionMaster=“TableQuestionMaster”;
静态最终字符串Q_ID=“_ID”;
静态最终字符串Module\u ID=“Module\u ID”;
静态最终字符串SubModule\u ID=“SubModule\u ID”;
静态最终字符串SubModuleQuestion\u ID=“SubModuleQuestion\u ID”;
静态最终字符串Question\u ID=“Question\u ID”;
静态最终字符串Title=“Title”;
静态最终字符串Module=“Module”;
静态最终字符串TitleDescription=“TitleDescription”;
静态最终字符串QuestionText=“QuestionText”;
静态最终字符串QuestionImage=“QuestionImage”;
静态最终字符串QuestionTemplate=“QuestionTemplate”;
静态最终字符串correctoroptionId=“correctoroptionId”;
//表格模板母版
静态最终字符串TableTemplateMaster=“TemplateMaster”;
静态最终字符串T_ID=“_ID”;
静态最终字符串Template\u ID=“Template\u ID”;
静态最终字符串Name=“Name”;
静态最终字符串Description=“Description”;
//表格问题选项
静态最终字符串TableQuestionOption=“TableQuestionOption”;
静态最终字符串TQP_ID=“_ID”;
静态最终字符串TQP_QuestionID=“QuestionID”;
静态最终字符串TQP\u OptionID=“TQP\u OptionID”;
静态最终字符串OptionText=“OptionText”;
//表类主控
静态最终字符串TableClassMaster=“TableClassMaster”;
静态最终字符串Class_ID=“_ID”;
静态最终字符串Class=“Class”;
私有静态字符串DB_PATH=“/data/data/com.cldonline.assessmenttool/databases/”;
私有静态字符串DB_NAME=“assessmenttool.DB”;
私有SQLiteDatabase-myDataBase;
私有最终上下文myContext;
/**
*建造师
*获取并保留传递的上下文的引用,以便访问应用程序资产和资源。
*@param上下文
*/
公共DBHelper(上下文){
super(上下文,DB_名称,null,1);
this.myContext=上下文;
}
/**
*在系统上创建一个空数据库,并用您自己的数据库重写它。
* */
public void createDataBase()引发IOException{
布尔值dbExist=checkDataBase();
if(dbExist){
//不执行任何操作-数据库已存在
}否则{
//通过调用此方法,将在默认系统路径中创建空数据库
//所以我们可以用我们的数据库覆盖那个数据库。
这是.getReadableDatabase();
试一试{
copyDataBase();
}捕获(IOE异常){
抛出新错误(“复制错误”)
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase db1;
// Static Final Variable database meta information
static final String DATABASE = "assesmenttool.db";
static final int DATABASE_VERSION = 1;
//Table Student Details
static final String TABLEStudent = "StudentDetails";
static final String S_ID = "_id";
static final String SchoolID = "SchoolID";
static final String SchoolName = "schoolname";
static final String StudentFirstName = "StudentFirstName";
static final String StudentLastName ="StudentLastName";
static final String StudentClassLevel ="StudentClassLevel";
static final String RollNo="RollNo";
static final String TestDate ="TestDate";
//Table Response Details
static final String TABLEResponse = "TableResponse";
static final String R_ID = "_id";
static final String StudentID = "StudentID";
static final String R_QuestionID = "QuestionID";
static final String QuestOptionID = "QuestOptionID";
//Table Question Master
static final String TableQuestionMaster = "TableQuestionMaster";
static final String Q_ID= "_id";
static final String Module_ID = "Module_ID";
static final String SubModule_ID = "SubModule_ID";
static final String SubModuleQuestion_ID ="SubModuleQuestion_ID";
static final String Question_ID= "Question_ID";
static final String Title = "Title";
static final String Module = "Module";
static final String TitleDescription = "TitleDescription";
static final String QuestionText = "QuestionText";
static final String QuestionImage = "QuestionImage";
static final String QuestionTemplate = "QuestionTemplate";
static final String CorrectOptionID = "CorrectOptionID";
//Table Template Master
static final String TableTemplateMaster = "TemplateMaster";
static final String T_ID= "_id";
static final String Template_ID= "Template_ID";
static final String Name = "Name";
static final String Description = "Description";
//Table Question Option
static final String TableQuestionOption = "TableQuestionOption";
static final String TQP_ID= "_id";
static final String TQP_QuestionID = "QuestionID";
static final String TQP_OptionID = "TQP_OptionID";
static final String OptionText = "OptionText";
//Table Class Master
static final String TableClassMaster = "TableClassMaster";
static final String Class_ID= "_id";
static final String Class = "class";
private static String DB_PATH = "/data/data/com.cldonline.assesmenttool/databases/";
private static String DB_NAME = "assesmenttool.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 DBHelper(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();
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.
this.getReadableDatabase();
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, null, 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, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// Override onCreate method
@Override
public void onCreate(SQLiteDatabase db) {
}
public List<String> getAllClasses(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableClassMaster;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> getAllOptions(String Qid){
List<String> options = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TableQuestionOption +" "+"where QuestionID ='"+Qid+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
options.add(cursor.getString(2));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return options;
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<Cursor> getData(String Query){
//get writable database
SQLiteDatabase sqlDB = this.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add(null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0) {
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
} catch(SQLException sqlEx){
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
} catch(Exception ex){
Log.d("printing exception", ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
}