[英]Android Database Read From Existing .sqlite FIle
I would like to read database from an existing file. 我想从现有文件中读取数据库。
I have copied the .sqlite database to asset folder. 我已将.sqlite数据库复制到资产文件夹。 I can see the .sqlite file under DDMS explorer in /data/data//databases/ 我可以在/ data / data // databases /中的DDMS Explorer下看到.sqlite文件
However when I run a "c = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type = 'table'", null);" 但是,当我运行“ c = db.rawQuery(“ SELECT count(*)FROM sqlite_master WHERE type ='table'”,null);“
It only returns the android_metadata table and not the other table from my database which was created in Firefox SQLite Manager. 它仅返回android_metadata表,而不返回我在Firefox SQLite Manager中创建的数据库中的其他表。
*NOTE, I will post both my DatabaseHandler and Database Activity files, for any modification please supply the FULL code (modify my existing files) and the reason for this is that I am new to Android and pieces of codes confuse me as to where in the class I need to paste, replace or append etc therefore I would appreciate FULL codes. *注意,我将同时发布我的DatabaseHandler和Database Activity文件,如果有任何修改,请提供完整代码(修改我现有的文件),其原因是我是Android的新手,而代码片段使我对其中的位置感到困惑该类,我需要粘贴,替换或附加等,因此,我将不胜感激。
Database Handler: 数据库处理程序:
package com.mypackage.lm;
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.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "lm.sqlite";
private static final int DB_VERSION = 1;
private static final String TABLE_LM = "lmtable";
private static final String LOG_TAG = "debugger";
private static final String DB_PATH = "context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile()";
private SQLiteDatabase myDB;
private Context context;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
@Override
public synchronized void close(){
if(myDB!=null){
myDB.close();
}
super.close();
}
/***
* Check if the database is exist on device or not
* @return
*/
private boolean checkDataBase() {
SQLiteDatabase tempDB = null;
try {
String myPath = DB_PATH + DB_NAME;
tempDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
Log.e("ts01 - check", e.getMessage());
}
if (tempDB != null)
tempDB.close();
return tempDB != null ? true : false;
}
/***
* Copy database from source code assets to device
* @throws IOException
*/
public void copyDataBase() throws IOException{
try {
InputStream myInput = context.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e("ts02 - copyDatabase", e.getMessage());
}
}
/***
* Open database
* @throws SQLException
*/
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/***
* Check if the database doesn't exist on device, create new one
* @throws IOException
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
System.out.println("Database DOES exist");
} else {
System.out.println("Database DOESN'T exist");
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e("ts03 - create", e.getMessage());
}
}
}
public List<String> getAllUsers(){
List<String> listUsers = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
//c = db.rawQuery("SELECT * FROM " + TABLE_LM , null);
//c = db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'" , null);
//c = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata' AND name != 'sqlite_sequence'", null);
c = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type = 'table'", null);
if(c == null) return null;
String name;
c.moveToFirst();
do {
name = c.getString(0);
listUsers.add(name);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
Log.e("ts04", e.getMessage());
}
db.close();
return listUsers;
}
}
Database Activity: 数据库活动:
package com.mypackage.lm;
import java.io.IOException;
import java.util.List;
import com.mypackage.lm.R.id;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DatabaseActivity extends MainActivity {
DatabaseHelper dbHeplper;
ListView lvUsers;
ListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_return);
dbHeplper = new DatabaseHelper(getApplicationContext());
try {
dbHeplper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
lvUsers = (ListView)findViewById(id.listViewDB);
List<String> listUsers = dbHeplper.getAllUsers();
if(listUsers != null){
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, android.R.id.text1,
listUsers);
lvUsers.setAdapter(adapter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Maybe I am wrong and this is not the answer, but if this should be Your path: 也许我错了,但这不是答案,但是如果这应该是您的道路:
private static final String DB_PATH = "context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile()";
Then You will have no file path. 这样您将没有文件路径。 You set a method inside the quotation marks, so the path will be: 您在引号内设置了一个方法,因此路径为:
context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile()lm.sqlite
I think what You wanted to do is: 我认为您想做的是:
private static final String DB_PATH = context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile();
OK, for some strange reason it worked, I uninstalled the APP from the Virtual Device then re-ran it, after the apk was re-installed I am able to see the database tables (android_metadata and lmtable). 好的,出于某种奇怪的原因,我从虚拟设备上卸载了该APP,然后重新运行它,在重新安装apk之后,我能够看到数据库表(android_metadata和lmtable)。
Now my next phase is to determine HOW my android will know that changes are made to the database and needs to be recopied despite "if DB exist" statement, I read about incrementing the DB version number so maybe that was the issue but as for now, uninstalling app from virtual device did the trick. 现在,我的下一个阶段是确定我的Android如何知道对数据库进行了更改,并且尽管有“如果存在数据库”语句,也需要将其复制,我读了有关增加数据库版本号的信息,所以也许这就是问题所在,但到目前为止,从虚拟设备上卸载应用程序就成功了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.