我试图创建一个Android应用程序,它将从现有数据库表中读取并获取单词。稍后我会在活动屏幕上显示这些字词。我已将数据库文件保存在ASSETS文件夹中,但它无法正常工作。任何帮助或建议将非常感谢。 这是我的数据库类,我尝试设置与数据库的连接。
public class DBManager extends SQLiteOpenHelper {
private static final String db_Word = "";
private static final String DATABASE_NAME = "SYFYB.sqlite";
private static final String DATABASE_TABLE = "WORDS";
private static final int DATABASE_VERSION = 1;
SQLiteDatabase db = null;
//public void dbCreator(Context dbContext)
//{
// try {
// db = dbContext.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
// } catch (Exception e){
// }
//}
public DBManager(Context context)
{
super(context, "SYFYB.sqlite", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void onSelect(SQLiteDatabase db, String selectCommand){
db.execSQL(selectCommand);
}
private String[] SELECT = {"WORDS"};
private Cursor ShowDATA(SQLiteDatabase dbFromMain){
SQLiteDatabase db;
db = this.getReadableDatabase(); // ERROR
Cursor cursor = db.query("WORDS",SELECT,null,null,null,null,null);
cursor.moveToFirst();
return cursor;
}
我在主要活动中使用此类,如下所示,
SQLiteDatabase dbFile = SQLiteDatabase.openDatabase("SYFYB.sqlite",null,SQLiteDatabase.OPEN_READONLY); //ERROR
String selectCommand = "select * from WORDS;";
DBManager dbObject = new DBManager(getApplicationContext());
dbObject.onSelect(dbFile, selectCommand);
注释的ERROR行显示为错误无法打开数据库。 我已经尝试将数据库文件保存为.db和.sqlite,但都没有工作。
更新: 我现在正在尝试这个代码,但是有一个"没有这样的表存在"错误。
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "SYFYB.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
System.err.println(context.getApplicationInfo().dataDir);
DB_PATH = context.getApplicationInfo().dataDir + File.separator
+ "databases" + File.separator;
System.out.println("-------"+DB_PATH);
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
System.out.println("=============");
myDataBase = SQLiteDatabase.openDatabase(DB_PATH+DB_NAME, null,
SQLiteDatabase.OPEN_READONLY);
} else {
myDataBase = this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
// throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
System.out.println("Database exists."+checkDB);
} catch (SQLiteException e) {
System.out.println("Database doesn't exist yet.");
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
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 onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public String fetchData() {
String SELECT = "select * from WORDS;";
System.out.println("------"+myDataBase);
Cursor cursor = myDataBase.rawQuery(SELECT, null);
String words = cursor.toString();
return words;
}
}
主要活动如下,
DataBaseHelper dataBaseHelper = new DataBaseHelper(getBaseContext());
try {
dataBaseHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
dataBaseHelper.getWritableDatabase();
// do your code
dataBaseHelper.openDataBase();
String dbWORDS = dataBaseHelper.fetchData();
textView.setText(dbWORDS);
答案 0 :(得分:1)
使用此
public class DataBaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "";
private static final String DB_NAME = "DBNAME";
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;
System.err.println(context.getApplicationInfo().dataDir);
DB_PATH = context.getApplicationInfo().dataDir + File.separator
+ "databases" + File.separator;
System.out.println(DB_PATH);
}
/**
* 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
// Toast.makeText(myContext, "already exist",
// Toast.LENGTH_LONG).show();
} 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);
// Toast.makeText(myContext, "already exist",
// Toast.LENGTH_LONG).show();
} catch (SQLiteException e) {
// database does't exist yet.
// Toast.makeText(myContext, "not already exist",
// Toast.LENGTH_LONG).show();
}
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 Input file to the output file
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();
}
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 onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
// 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.
}
使用数据库
DataBaseHelper dataBaseHelper = new DataBaseHelper(getBaseContext());
try {
dataBaseHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
SQLiteDatabase sqld = dataBaseHelper.getWritableDatabase();
Cursor cursor = sqld.rawQuery("select * from your_table_name", null);
if (cursor.moveToFirst()) {
do {
int id =cursor.getInt(cursor.getColumnIndex("columnName"));
} while (cursor.moveToNext());
}
sqld.close();
答案 1 :(得分:1)
您无法直接将应用程序中ASSETS文件夹的文件作为资源写入,因为文件夹是只读的。您必须先将数据库从资产文件夹复制到SD卡,然后才能阅读&写进去。
尝试下面的代码从assests中读取sqlite数据库并将其复制到sdcard中以使用它。
public class DataBaseHelper extends SQLiteOpenHelper {
private Context mycontext;
//private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db
public SQLiteDatabase myDataBase;
public DataBaseHelper(Context context) throws IOException {
super(context,DB_NAME,null,1);
this.mycontext=context;
boolean dbexist = checkdatabase();
if (dbexist) {
//System.out.println("Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}
}
public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if(dbexist) {
//System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch(IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
//checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
checkdb = dbfile.exists();
} catch(SQLiteException e) {
System.out.println("Database doesn't exist");
}
return checkdb;
}
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("/data/data/(packagename)/databases /(datbasename).sqlite");
// transfer byte to inputfile to 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();
}
public void opendatabase() throws SQLException {
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close() {
if(myDataBase != null) {
myDataBase.close();
}
super.close();
}
}
答案 2 :(得分:0)
实际上有两种获取db文件的方法,一种是通过其名称,另一种是通过路径。 1.Name方法使用默认路径 2.可以修改第二种方法以使用自定义路径。
String DBpath = context.getAssets()+File.seperator+ "databases" + File.separator+DBName;
SQLiteDatabase db = openOrCreateDatabase(DBpath,MODE_PRIVATE,null);
像这样你可以使用一个辅助类或没有一个在一个assest文件夹中打开一个数据库。在你的情况下你正在使用它。然后将这个代码复制到createDatabase方法中。