【发布时间】:2013-09-16 16:07:30
【问题描述】:
我正在尝试使用 Cordova 创建 'Offline Dictionary Android App。我已经使用SQLite database browser 创建了 sqlite 数据库。数据库文件是test.db,它有一个表test,其中有两个字段'_id' 是INTEGER PRIMARY KEY 和'value' 是TEXT。还插入了一些记录。
我试过这些都没有运气:
- import/export to android sqlite database
- Can't access pre populated SQLite database using PhoneGap/Cordova in Android
我已经能够收集到以下代码。 我希望我的第三次尝试能够成功,所以我在这里寻求专家的帮助。
我做了什么
我将test.db sqlite 数据库文件放在我的android 项目的assets 目录中。我有 MainActivity.java 文件,其中包含以下代码:
MainActivity.java
package com.example.sqlite;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Bundle;
import android.util.Log;
import org.apache.cordova.*;
public class MainActivity extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
try{
System.out.println("----------Copying Database -----------");
copyDataBase("test.db");
} catch (IOException ioe){
System.out.println("----------Error Copying Database -----------");
ioe.printStackTrace();
}
}
private void copyDataBase(String dbname) throws IOException {
// Open your local db as the input stream
String pkg = this.getApplicationContext().getPackageName();
InputStream myInput = this.getAssets().open(dbname);
// Path to the just created empty db
String outFileName = "/data/data/"+ pkg + "/databases/" + dbname;
// 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();
}
}
和script.js 文件包含以下脚本:
script.js
(function($, undefined){
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady(){
var db = window.openDatabase(
'test.db',
'1.0.0',
'Test Database',
64 * 1024
);
db.transaction(function(tx){
tx.executeSql(
'SELECT * FROM test', [], function(tx, result){
console.log("Query Success");
console.log('Total Rows :' + result.rows.length);
},function(tx, error) {
console.log('An Error Occured (Qry) : ' + error.message);
}
)
}, function(error){
console.log('An Error Occured : ' + error.message);
}, function(){
console.log("Transaction Success");
})
}
})(jQuery);
我已经在emulator 和physical device 中启动了我的应用程序,并得到了相同的错误响应,即“没有这样的表:测试”。我找到了test.db insdie data/data/MY_PACKAGE/databases/。我使用 eclipse pulled 那个数据库文件并在 SQLite Database browser 中打开,并且有 test 表,其中包含我填充的一些记录。
我正在使用 cordova 2.6.0 并在 android 4.2 上测试我的应用程序。我的设备没有植根(如果不影响则忽略)。
可视化场景的屏幕截图:
为什么即使有表格,我也会收到“没有这样的表格”错误?
请帮忙。
【问题讨论】:
-
等待响应直到 1 小时。还没有有用的手。
标签: android database sqlite cordova