How to update data using room database? - android

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

Related

Insert data into database in Android

This is my first Application with database, I hope that someone can help me to understand this problem. I have this insert method:
public long insertData(String name, int password){
....
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_PASSWORD, password);
return db.insert(DBHelper.TABle_NAME, null, contentValues);
}
I can insert few data with this method, but what about if I have thousands of rows? how can I insert all these data into database? where can I write all these data, in extra class or what?
As others have said, you'll need to do some sort of iteration.
Efficiency can be gained by performing a bulk transaction. Here's an example:
public int bulkInsert(#NonNull ContentValues[] values) {
int insertCount = 0;
SQLiteDatabase db = mSqlHelper.getWritableDatabase();
try {
db.beginTransaction();
for (ContentValues value : values) {
if (db.insertOrThrow(tableName, null, value) == -1) {
throw new Exception("Unknown error while inserting entry in database.");
}
insertCount++;
}
db.setTransactionSuccessful();
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred while bulk-inserting database entries.\n" + e.getMessage(), e);
} finally {
db.endTransaction();
}
return insertCount;
}
There is no 'bulk load' facility that I'm aware of.
You'd just have to spin through the list, and insert the items.
You might want to think about why you're potentially trying to insert thousands of items into a database on a hardware-limited device like a phone or a tablet.
Might it be better to put the data on a server, and create an API that you can use to load data (for display) by pages?
you can do it the same way, that you do with few data, you only need to catch the thousands rows to insert into your database using your method, you can use asyntask, or a service to do that
You can use the same method to insert any amount of records, whether it's 1 or 1,000. Use a loop to call your insert method and add your records to your database. Consider putting your database executions in an AsyncTask to prevent your UI thread from hanging.
Your data can come from anywhere, as long as it's formatted to fit your function parameters String, int

add large amount of data in SQLite android

I am new to android and maybe its a silly question but i am not getting it. See i am designing a game in which we give scores to some persons. So i want to store the names of the persons in a database while installation and then their scores set to 0 initially which will be updated according to what the users select. Here i am not able to figure out that how should i enter the data as it will be around 100 names and their scores. Using INSERT INTO() statement will make it like 100 statements. So is there any short method like can we do it through strings or something. Just guessing though. Any help would be appreciated.
You don't hard-code names or scores into your SQL statements. Instead, you use parameters.
var command = new SQLiteCommand()
command.CommandText = "INSERT INTO Scores (name, score) VALUES(#name, #score)";
command.CommandType = CommandType.Text;
foreach (var item in data)
{
command.Parameters.Add(new SQLiteParameter("#name", item.Name));
command.Parameters.Add(new SQLiteParameter("#score", item.Score));
command.ExecuteNonQuery();
}
and then just loop through all of the names and scores.
I recommend you using a transaction.
You can archive this stating you want to use a transaction with beginTransaction(), do all the inserts on makeAllInserts() with a loop and if everything works then call setTransactionSuccessful() to do it in a batch operation. If something goes wrong, on the finally section you will call endTransaction() without setting the success, this will execute a rollback.
db.beginTransaction();
try {
makeAllInserts();
db.setTransactionSuccessful();
}catch {
//Error in between database transaction
}finally {
db.endTransaction();
}
For the makeAllInserts function, something like this could work out:
public void makeAllInserts() {
for(int i = 0; i < myData.size(); i++) {
myDataBase = openDatabase();
ContentValues values = new ContentValues();
values.put("name", myData.get(i).getName());
values.put("score", myData.get(i).getScore());
myDataBase.insert("MYTABLE", nullColumnHack, values);
}
}
If you also want to know about the nullColumnHack here you have a good link -> https://stackoverflow.com/a/2663620/709671
Hope it helps.

How to clean/delete greenDao database

Currently I'm doing it like this:
DaoMaster.dropAllTables(getDb(), true);
DaoMaster.createAllTables(getDb(), true);
but then, when I'm trying to add entity to the database, I'm getting crash log saying that this table isn't exist
Edit1:
I know that it happens because the db is locked and tables wasn't created yet. So I'm reducing this problem to the problem - how to know if the tables are locked in grrenDao/Sqlite?
How about using something like this for each table?
daoSession.getSometableDao().deleteAll();
Until now, I don't worry if tables are locked or not; in my case, i do the following and it works:
First, when App.onCreate executes, I make the standard initializations.
T.devOpenHelper= new DaoMaster.DevOpenHelper(context, "mydatabase", null);
T.sqLiteDatabase= T.devOpenHelper.getWritableDatabase();
T.daoMaster= new DaoMaster(T.sqLiteDatabase);
T.daoSession= T.daoMaster.newSession();
T.dao_myEntity= T.daoSession.getMyEntityDao();
In some moment in the future I drop and recreate all tables, just like you:
T.daoMaster.dropAllTables(T.sqLiteDatabase, true);
T.daoMaster.createAllTables(T.sqLiteDatabase, true);
But in my case, then I can immediately insert a new entity:
MyEntity e= new MyEntity();
e.setId_ticket(1L);
e.setDescription("wololo");
long id= T.dao_myEntity.insert(e);
Log.d(G.tag, "T.erase_all: id: " + id); // prints "T.erase_all: id: 1"
I hope it helps.
public static void clearDatabase(Context context) {
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(
context.getApplicationContext(), Constants.SQL_DB_NAME, null);
SQLiteDatabase db = devOpenHelper.getWritableDatabase();
devOpenHelper.onUpgrade(db,0,0);
}
For now it can be done like that:
for (AbstractDao abstractDao : mDaoSession.getAllDaos()){
abstractDao.deleteAll();
}
I upgraded the schemaVersion in build.gradle to pass through this error
Try this one:
QueryBuilder<cart> qb = SQLConfig.cartDao.queryBuilder();
List<cart> mUpadateData = qb.where(cartDao.Properties.Product_sku.eq(skuApi)).list();
SQLConfig.cartDao.deleteInTx(mUpadateData);

Saved data lost when I restart the application(android)

I'm saving some records through my application in SQLite database and later retrieving those records for future use.
It's working fine until I close my application.
When I close my application all the previously saved record becomes zero.
Here is the code:--
public long insertAlbum(long Outlet_id,long user_id,String Remarks,String PhotoName,String ReportId,String Date,String Status,String LocalRepId)
{
long rowId=0;
ContentValues initialValues = new ContentValues();
initialValues.put("web_AlbumId", 0);
initialValues.put("OutletId", Outlet_id);
initialValues.put("Remarks", Remarks);
initialValues.put("UserId", user_id);
initialValues.put("Usr_Entdt", Date);
initialValues.put("PhotoName", PhotoName);
initialValues.put("ApprovedYN", "Pending");
initialValues.put("Status", Status);
initialValues.put("ReportId", ReportId);
initialValues.put("LocalReportId", LocalRepId);
try
{
myDataBase.beginTransaction();
rowId= myDataBase.insertOrThrow("Album", null, initialValues);
myDataBase.setTransactionSuccessful();
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
myDataBase.endTransaction();
}
return rowId;
This shouldn't happen.
Sounds to me like you're recreating the database when you're opening the database.
Check your code to make sure it's correct
Without seeing your code, it's hard to say what's going on. However, my suspicion is that your code is ALWYAYS creating the database. Are you extending the SQLiteOpenHelper class to create your database? Check there or post the code for further assistance.
Go to to folder where your Sqlite Db file created and check in that file whether the data you saved is present or not . If the data is present in the DB then you need to Retrieve the data from DB

Android transaction or trigger?

I am working on a fuel use application which will run on Android 1.6 onwards. The bundled SQLite on v1.6 doesn't do foreign keys, so I've had to handle it manually. So far, I have done this using an Android transaction:
public static long addFuelUp(String registrationNumber, String date)
{
SQLiteDatabase db = uKMpgData.getReadableDatabase();
long result = -1;
ContentValues values = new ContentValues();
Cursor vehicleCursor = VehicleDataProvider.getVehicle(registrationNumber);
if(vehicleCursor.moveToNext())
{
Cursor fuelUpsCursor = getFuelUps(registrationNumber, date);
if(!fuelUpsCursor.moveToNext())
{
db.beginTransaction();
try
{
values.put(REGISTRATION_NO_COLUMN, registrationNumber.replace(" ", ""));
values.put(DATE_TIME_COLUMN, date);
result = db.insertOrThrow(FUEL_USE_TABLE_NAME, null, values);
db.setTransactionSuccessful();
}
catch(SQLException e)
{
Log.d("addFuelUp", e.getMessage());
}
finally
{
db.endTransaction();
vehicleCursor.close();
fuelUpsCursor.close();
}
}
}
return result;
}
I.e. fuel data cannot be entered unless there is a matching vehicle registration number in the database.
My question is, is there a better way to do this? I'm not a database expert, but I know you can set up triggers to enforce rules - are triggers more suited to handle constraints?
Cheers,
Barry
Triggers would be a good solution to this problem.
In fact there is an automated way to generate triggers for simulating foreign keys. SQLite for PC provides a utility called "genfkey" which can examine an existing database which uses foreign keys and outputs the corresponding triggers.

Categories

Resources