我想在Android应用程序中引用SQLite DB文件。我从eclipse上将它推送到模拟器上的SD卡上,然后我正在运行安装在手机内存上的应用程序。该代码用于基于查询的数据检索。
我正在使用以下类文件。
public class ExternalStorageReadOnlyOpenHelper {
private SQLiteDatabase database;
private File dbFile;
private SQLiteDatabase.CursorFactory factory;
public static final String KEY_ROWID1= "_id";
public static final String KEY_num1= "num1";
public static final String KEY_words1 = "words1";
private static final String DATABASE_TABLE1 = "dictionary";
public ExternalStorageReadOnlyOpenHelper(
String dbFileName) {
// this.factory = factory;
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new AndroidRuntimeException(
"External storage (SD-Card) not mounted");
}
File appDbDir = new File(
Environment.getExternalStorageDirectory(),
"SMSconfApp1");
if (!appDbDir.exists()) {
appDbDir.mkdirs();
}
this.dbFile = new File(appDbDir, dbFileName);
}
public boolean databaseFileExists() {
return dbFile.exists();
}
private void open() {
if (dbFile.exists()) {
database = SQLiteDatabase.openDatabase(
dbFile.getAbsolutePath(),
factory,
SQLiteDatabase.OPEN_READONLY);
}
}
public void close() {
if (database != null ) {
database.close();
database = null;
}
}
public SQLiteDatabase getReadableDatabase() {
return getDatabase();
}
private SQLiteDatabase getDatabase() {
if (database==null) {
open();
}
return database;
}
public String getID(String pqr, SQLiteDatabase db) throws SQLException
{
String data="";
Cursor mCursor =
db.query(true, DATABASE_TABLE1, new String[] {
KEY_ROWID1,
KEY_num1,
KEY_words1
},
KEY_words1 + "=?",
new String[]{pqr},
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
if (mCursor.moveToFirst()){
do{
data = mCursor.getString(1);
// do what ever you want here
}while(mCursor.moveToNext());
}
mCursor.close();
}
return data;
}
}
我的活动如下
public class SDcardDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv= new TextView(this);
setContentView(R.layout.main);
SQLiteDatabase db;
String DBFile="SMSconfApp1";
String number=null;
// ExternalStorageReadOnlyOpenHelper.open();
ExternalStorageReadOnlyOpenHelper obj= new ExternalStorageReadOnlyOpenHelper(DBFile);
if(obj.databaseFileExists())
{
db=obj.getReadableDatabase();
number=obj.getID("hi", db);
obj.close();
}
tv.setText(number);
setContentView(tv);
}
}
当我运行应用程序时,它不显示来自数据库的任何检索。我没有得到代码中的错误。有什么帮助吗?
答案 0 :(得分:1)
此代码期望DB位于此位置:
MNT \ SD卡\ SMSconfApp1 \ SMSconfApp1
首先,App Dir构造为:
File appDbDir = new File( Environment.getExternalStorageDirectory(),
"SMSconfApp1");
这将导致:mnt \ sdcard \ SMSconfApp1 \,稍后一旦添加了DB文件名,它就变成了mnt \ sdcard \ SMSconfApp1 \ SMSconfApp