gpt4 book ai didi

javascript - SQLite 数据库在 Android 4.4 中不工作

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:07 24 4
gpt4 key购买 nike

我正在为我的 PhoneGap 项目使用 SQLite 数据库。除了 Android 4.4.0+ 之外,我测试过的所有其他操作系统都在填充数据库。

访问数据库的代码如下:-

public class MathWhiz extends CordovaActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
super.loadUrl(Config.getStartUrl());
SharedPreferences sp = getSharedPreferences("MYPREFS",
Activity.MODE_PRIVATE);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

// If no shared prefs exist, e.g. first install, it doesn't matter - the
// following will return false as a default
Boolean database_copied = sp.getBoolean("database_copied", false);
if (!database_copied) {
try {
String pName = this.getClass().getPackage().getName();

this.copy("Databases.db", "/data/data/" + pName
+ "/app_database/");
this.copy("sample.db", "/data/data/" + pName
+ "/app_database/myFile/");
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("database_copied", true);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}

}

void copy(String file, String folder) throws IOException {

File CheckDirectory;
CheckDirectory = new File(folder);
if (!CheckDirectory.exists()) {
CheckDirectory.mkdir();
}
InputStream in = getApplicationContext().getAssets().open(file);
OutputStream out = new FileOutputStream(folder + file);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();

}

}

这就是我使用数据库的方式:-

window.openDatabase("sampleDB", "1.0", "sample", 200000);

任何人都可以指出我需要做哪些更新才能使其在 Android 4.4 + 上运行吗?谢谢

最佳答案

试一试..它运作良好...

public boolean copyDataBaseFromAssets(Context c) throws IOException {

if(android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/"+ DATABASE_NAME;
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"+DATABASE_NAME;

String pathToDatabaseFileInAssetFolder = DATABASE_NAME;
String pathToDatabaseFileInSystem = DB_PATH;


this.getReadableDatabase();

> getReadableDatabase 函数用于数据库导入代码

        AssetManager assetManager = c.getResources().getAssets();
InputStream inputStream = null;

try {

inputStream = assetManager.open(pathToDatabaseFileInAssetFolder);
} catch (IOException ex) {

return false;
}

if (inputStream != null) {

OutputStream outputStream = new FileOutputStream(pathToDatabaseFileInSystem);

byte[] buffer = new byte[1024];
int length;

while ((length = inputStream.read(buffer)) > 0) {

outputStream.write(buffer, 0, length);
}

outputStream.flush();
outputStream.close();
inputStream.close();

Log.d(TAG, "Database is copied");
return true;
}

return false;
}

关于javascript - SQLite 数据库在 Android 4.4 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21407444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com