I have created the database in flutter using sqflite plugin. I created android home screen widgets for my app in android native. Now I need to fetch the data from SQLite. That is I am trying to fetch the data using Android Native sqflite Package from the SQLite db. Is that possible?
> There is No Limit on Flutter
Basic Rules of Sqlite, you need to remember
sqflite is works on Top of SQLite Database
so , when ever flutter plugin creates the database ,it was availible for native code (verify folder structure)
You can OpenDatabase by giving Database Path to SQLiteDatabase on Native Android or IOS
finally you can Read table data by query()
private fun accessDB(){
try {
GlobalScope.launch {
var db:SQLiteDatabase = SQLiteDatabase.openDatabase(getDatabasePath("epistle.db").absolutePath,null,SQLiteDatabase.OPEN_READWRITE);
Log.d(MainActivity::class.java.name , "Database Path "+db.path.toString())
Log.d("" , "Database version "+db.version.toString())
var cursor = db.query("userInfo",null,null,null,null,null,null)
cursor?.let {
while (cursor.moveToNext()){
var columnNames =cursor.columnNames
columnNames.forEach {
Log.d(
MainActivity::class.java.name,
"$it "+cursor.getString(cursor.getColumnIndex(it))
)
}
}
}
}
}catch (e:Exception){
e.printStackTrace();
}
}
MainActivity: Database Path /data/u
MainActivity: id 1
MainActivity: uid XfXCx613bKWl0EuDU
MainActivity: username Lee And May
MainActivity: email yepi1#yep.com
MainActivity: location US
MainActivity: isBiometricEnabled 0
MainActivity: isNotificationsEnable
MainActivity: morning 152.549
MainActivity: evening 166.529
MainActivity: plan Basic
MainActivity: lattitude 0
MainActivity: lognitude 0
MainActivity: userID XfXCx613bKWl0E
MainActivity: theme 2
MainActivity: premiumStartDate null
MainActivity: premiumEndDate null
MainActivity: isPremium 0
Related
In my project, I am trying to save data into a sqllite database and trying to read those data once its saved. I am able to write all the data in the database but while trying to retrieve the data then I am getting unable to start activity: Kotlin.kotlinNullPointerException error. I followed all the recommendation by android suggestion but still getting this error. Any help is appreciated.
Language Used
Kotlin
Error
Unable to start activity ComponentInfo: kotlin.KotlinNullPointerException
Code
noteList = dbHandler!!.readNotes()
Read Code
fun readNotes(): ArrayList<Notes>
{
var db=readableDatabase
val list:ArrayList<Notes> = ArrayList()
var selectAll = "SELECT * FROM " + TABLE_NAME
var cursor: Cursor = db.rawQuery(selectAll, null)
if(cursor.moveToFirst())
{
do {
var note = Notes()
note.id=cursor.getInt(cursor.getColumnIndex(KEY_ID))
note.noteName = cursor.getString(cursor.getColumnIndex(KEY_NOTE_NAME))
list.add(note)
}
while (cursor.moveToNext())
}
return list
}
Steps Checked
1) Activity is presented in Android Manifest File
2) Data's are stored in the database
3) Text Views castings are done properly
The dbHandler might be null. using !! asserts that the object is not null. Check if you have initialised the dbHandler or post the whole code
I updated my AbstractFooEntity class by adding an integer field like below, and I bumped the DB version (the DB is initialized with new DatabaseSource(context, Models.DEFAULT, DB_VERSION).
#Entity
abstract class AbstractFooEntity {
// this was in DB schema v1
String someField;
// added in DB schema v2
int newField = 0;
}
When I deploy this code and the (automatic) DB migration is performed when the user runs the new version of the Android app, I get the following error at runtime: "Cannot add a NOT NULL column with default value NULL".
What's the proper way to annotate the entity so that the framework correctly handles the automatic DB migration in this scenario?
I found a solution of this.
database.execSQL("ALTER TABLE table_name ADD COLUMN colum_name INTEGER DEFAULT 1 not null");
add the command : "DEFAUT value" after data type will solve your problem.
There are two options, first one is probably to be preferred - in the second one, you need to handle possible nullpointers in the code:
option 1
#Entity
abstract class AbstractFooEntity {
...
#Column(value = "0")
int newField;
}
option 2
#Entity
abstract class AbstractFooEntity {
...
Integer newField;
}
I am using Room database and I want to update a row. I am able to update the row but getting this warning
12-05 20:59:17.635 29363-29372/com.example.parmarravi21.recyclerviewiv W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.example.parmarravi21.recyclerviewiv/databases/RecP10' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
This is my code
//defining database
db = Room.databaseBuilder(getActivity(), AppDatabase.class, "RecP10")
.fallbackToDestructiveMigration()
.allowMainThreadQueries().build();
TimeDateModel timeDateModel = new TimeDateModel(positionTime, TimeMode);
ContentValues contentValues = new ContentValues();
contentValues.put("posItem", timeDateModel.getPosItem());
contentValues.put("TimeDateMode", timeDateModel.getTimeDateMode());
if (db.timeDao().getItemAtTimePos(positionTime) != null) {
Log.e(TAG, "updated database");
db.beginTransaction();
try {
db.getOpenHelper().getWritableDatabase().update("Datetime", 0,
contentValues, "posItem =" + positionTime, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction(); // commit or rollback
db.close();
}
} else {
Log.e(TAG, "New item added");
db.timeDao().insertAll(timeDateModel);
}
I have also tried the dao update function but the data is not updating .
db.timeDao().update(timeDateModel);
I am new to database in android please help me out .
Github link for complete code
#Query("UPDATE Test SET test_name=:arg1,test_startDate=:arg2,test_endDate=:arg3,test_location=:arg4,test_ringerMode=:arg5,test_latitude=:arg6,test_longitude=:arg7 WHERE testId = :arg0")
fun updateTest( testId: Int,testName:String,testStartTime:String,testEndTime:String,testLocation:String,testRingerMode:Int,testLatitude:Double,testLongitude:Double)
Try coding this way.
Using an #Update annotation should do the trick , and according to the Android developer Documentation, you shouldn't perform database Queries on the main Thread ,thus might cause your database issues
Something like these
#Update
void updateTimeEntry(TimeEntry timeEntry)
with TimeEntry being the name of your model class
I'm actually working on a cordova application that is reading (not writing) a .mbtiles file. That is a database filed with tiles in order to show an offline map with leaflet.
Everything concerning the file (call it test.mbtiles) is working : downloading and openning. But there is still a big issue. I'm not able to read the tables. Here's the non functionnal sample of my code :
getTileUrl: function (tilePoint, callBack) {
var x = tilePoint.x;
var y = tilePoint.y;
var z = tilePoint.z;
var base64Prefix = 'data:image/png;base64,';
var db2 = new window.sqlitePlugin.openDatabase({name: 'test.mbtiles'});
db2.transaction(function(tx) {
tx.executeSql("SELECT tile_data FROM images INNER JOIN map ON images.tile_id = map.tile_id WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?", [z, x, y], function (tx, res) {
if(res.rows.length>0) {
console.log("success");
var src = base64Prefix + res.rows.item(0).tile_data;
callBack(src);
}
else {
console.log("response : no data");
}
}, function (tx, er) {
console.log('error with executeSql : ', er.message);
return;
});
});
}
So now everytime I try to use the offline map (using tiles from the test.mbtiles which is present on the device) i get this error :
error with executeSql : no such table: images (code 1): , while compiling: SELECT tile_data FROM images INNER JOIN map ON images.tile_id = map.tile_id WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?
So I assume that the file I'm getting, the test.mbtiles is not good because it doesn't have any images table. But that's wrong. I used SQLite Database Browser in order to look at my database scheme, and found that the images table is here and filled with the right data.
Has anyone else had this error and know how to fix it ?
Btw I'm using latest release versions of SQLite Plugin and Cordova, and mainly testing on android (will port to ios if android works). And as much as possible i would like to use only .js files, no addition in any java class or such (would destroy the whole workflow).
Thanks.
The MBTiles spec stores tiles in a table called tiles, not images.
I am trying to fetch data from Sqlite database using a sqlite plug-in in phonegap but I seem to be missing something. It doesn't report error when I checked the logcat but instead the database was opened successfully but my code won't fetch the data.
Below is my code so far...
function ViewData(id){
var db = window.sqlitePlugin.openDatabase("mydb", "1.0", "mydb", 100000);
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM mytable WHERE userid=?', [id],
function(transaction, result) {
var row = result.rows.length;
if(row>0){
//fetch saved data
alert(result.rows.item(0)['lname']);
}
},errorHandler);
},errorHandler,nullHandler);
return ;
}
Note:
1. The error handler, success handler and null handler are well coded.
Please, any help is appreciated.
Sorry guys, i was calling the function before onDeviceReady