I have two android apps (one written in js(using phonegap) the other in java). Both need to access one SQLite DB. Yes it's possible.
In my js file I use Cordova-sqlite-storage to create and insert data into a db:
var db = window.sqlitePlugin.openDatabase({name: "CAC.db", location: 1});
db = sqlitePlugin.openDatabase({name: "CAC.db", location: 2, createFromLocation: 1});
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
// demonstrate PRAGMA:
db.executeSql("pragma table_info (test_table);", [], function(res) {
console.log("PRAGMA res: " + JSON.stringify(res));
});
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["MY ID", 100], function(tx, res) {
db.transaction(function(tx) {
tx.executeSql("select data as dt from test_table;", [], function(tx, res) {
var id = res.rows.item(0).dt;
console.log("res.rows.item(0).cnt: " + id);
});
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
Then I use this answer to try to connect the java app to my preexisting db:
Context sharedContext = null;
try {
sharedContext = this.createPackageContext("com.my.app", Context.CONTEXT_INCLUDE_CODE);
if (sharedContext == null) {
return;
}
} catch (Exception e) {
String error = e.getMessage();
return;
}
DbAdapter sharedDBadapter = new PerformerDbAdapter(sharedContext);
sharedDBadapter.open();
However I am required to use this code in my js app:
DBadapter hostDBAdapter = new DbAdapter(getApplicationContext());
performerDBadapter.open();
to try to get its context. (But obviously I can't because this code^ is java). So I tried to get the context using this answer.(Context context=this.cordova.getActivity().getApplicationContext();
) But am not sure where to add this, and I am not even sure if this code would work anyways.
My questions are:
- Where do I add this code in my application?
- Am I on the right path?
- What is the best way to connect a js app and Java app to the same SQLite Dtatabase on Android? (Examples would be very helpful)
INFO:
Android 5.1, Cordova 5.0
UPDATE:
I already have android:sharedUserId="my.app"
in both apps.