我正在尝试创建 'Offline Dictionary Android App
使用Cordova . 我使用 SQLite database browser
创建了sqlite数据库 . 数据库文件是 test.db
,它有一个表 test
,有两个字段'_id',即 INTEGER
PRIMARY KEY
和'value',即 TEXT
. 还插入了一些记录 .
我试过这些没有运气:
我已经能够收集以下代码 . 我希望我的第三次尝试成功,所以我来这里寻求专家的帮助 .
WHAT I HAVE DONE
我把 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
中启动了我的应用程序,并得到了与'no such table : test'相同的错误响应 . 我找到了 test.db
insdie data/data/MY_PACKAGE/databases/
. 我 pulled
该数据库文件使用eclipse并在 SQLite Database browser
中打开,并且 test
表包含我已填充的一些记录 .
我正在使用cordova 2.6.0并在android 4.2上测试我的应用程序 . 我的设备没有root(如果不影响则忽略) .
可视化场景的屏幕截图:
Why am I getting the 'no such table' error even there is a table ?
请帮忙 .
2 回答
只需检查您是否已正确完成数据库中的连接,然后创建一个表,插入一些数据,然后从Cordova和数据库浏览器中选择您放在表上的内容 .
也许你不需要把.db,先试试这个代码
我完全测试你的代码 . 我解决了在js代码中编写完整路径:
..并在重新运行项目之前清理项目 .
希望这对你有所帮助 .
问候