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);
Related
I want to use GreenDAO for persistence, but I cannot get it to persist my data.
The data is saved and loaded correctly as long as the application is not restarted.
Once i swipe the app away and reopen it from scratch, GreenDAO does not see the previous data (both on the emulator and real device).
This is my entity:
#Entity
public class TestSingleEntity {
#Id(autoincrement = true)
Long id;
int someNumber;
public TestSingleEntity(int someNumber) {
this.someNumber = someNumber;
}
#Generated(hash = 787203968)
public TestSingleEntity(Long id, int someNumber) {
this.id = id;
this.someNumber = someNumber;
}
#Generated(hash = 1371368161)
public TestSingleEntity() {
}
// ... some more stuff
}
This is how I insert entities to database:
Random rnd = new Random();
TestSingleEntity singleEntity = new TestSingleEntity();
singleEntity.setSomeNumber(rnd.nextInt());
DaoSession session = ((MyApp)getApplication()).getDaoSession();
TestSingleEntityDao dao = session.getTestSingleEntityDao();
dao.insert(singleEntity);
Log.d("tgd", "Inserted an entity with id " + singleEntity.getId());
And this is how I read them:
Query query = dao.queryBuilder().orderAsc(TestSingleEntityDao.Properties.SomeNumber).build();
StringBuilder builder = new StringBuilder();
List<TestSingleEntity> result = query.list();
Log.d("size", result.size());
for (TestSingleEntity testSingleEntity : result) {
Log.d("entity", testSingleEntity.toString());
}
As I have said, as long as I stay in the app (moving around in different activities is okay), everytime the insert is called, a new entity with a new ID is created. As soon as I relaunch the app, it goes back to square one.
The setup was taken directly from the GitHub page. What am I doing wrong? Thanks
Disclaimer: GreenDAO has gone through major changes since I last used it so this is purely based on reading their code on the github.
Apparently GreenDAO's poorly documented DevOpenHelper drops all tables on upgrade, so the real question is why is onUpgrade being called when clearly there hasn't been a change to the schema version. Try to look for the log line that mentions dropping the tables as described in the template for DevOpenHelper.
Regardless, using OpenHelper instead should fix the issue.
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 have an app that inserts data into a database with 2 tables (project and alvara)
The insertion method for the second table depends on what type the first table gets. (1 or 2) for resumed idea.
This is a method that I made for looking into the second table with cursor. If it finds, it sets in setters from alvara_db class. And later on, I use getters to show info on textviews in another activity. The issue is that it's not setting info at all. Is anything wrong in my Cursor?
Thanks in advance!
public ArrayList<alvara_db> getAlvaras(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<alvara_db> projects = new ArrayList<>();
String[] project = new String[]{String.valueOf(tipoprojetoid)};
Cursor cur = db.rawQuery("SELECT placa, proj_exec, resp_tec, rtnum, parecer FROM alvara WHERE projetoid = ?", project);
cur.moveToFirst();
alvara_db alvaras = new alvara_db();
alvaras.setPlaca(cur.getInt(cur.getColumnIndex("placa")));
alvaras.setProj_exec(cur.getInt(cur.getColumnIndex("proj_exec")));
alvaras.setResp_tec(cur.getString(cur.getColumnIndex("resp_tec")));
alvaras.setRtnum(cur.getInt(cur.getColumnIndex("rtnum")));
alvaras.setParecer(cur.getString(cur.getColumnIndex("parecer")));
projects.add(alvaras);
return projects;
}
Fragment where I call getAlvaras method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalhes_projeto_alvara);
db.getAlvaras();
placa = alvaras.getPlaca();
resp_tec = alvaras.getResp_tec();
proj_exec = alvaras.getProj_exec();
rtnum = alvaras.getRtnum();
}
You are not using the returned value from db.getAlvaras().
Instead the alvaras variable in your second snippet is something that is likely not initialized - the code you posted does not show that exactly.
(In addition, you might want to check the return value of moveToFirst() in case the query matches no rows, and add a do-while loop to retrieve more than one row.)
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.
I created a database in my class like
public final String CRAZY_ALARM_DB_NAME = "CrazyDb";
public final String CRAZY_ALARM_TABLE_NAME = "CrazyTable";
alarmDB = this.openOrCreateDatabase(
CRAZY_ALARM_DB_NAME, MODE_PRIVATE, null
);
alarmDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ CRAZY_ALARM_TABLE_NAME
+" (REQ_CODE INT(3),DAY INT(3),HOUR INT(3)"
+",MINUTE INT(3),COUNT INT(3),REPEAT INT(3)"
+",DAYS VARCHAR2(100),SUN INT(3),MON INT(3),"
+"TUE INT(3),WED INT(3),THU INT(3),FRI INT(3),"
+"SAT INT(3));"
);
cr = alarmDB.rawQuery("SELECT * FROM "
+CRAZY_ALARM_TABLE_NAME, null
);
so i want to use this database in another class. I am also do the same thing ,i wrote "openorcreate "code in another class and also cursor..
but it gave an exception like no such table while compiling ... at cursor line..
please help me.
You should use an SQLiteOpenHelper-class to access and maintain your Database.
If you do so, you can (in whatever class you like) use the following lines to get a read or writable database:
YourSQliteOpenHelper db_con = new YourSQliteOpenHelper(getApplicationContext());
// Readable:
SQLiteDatabase db = db_con.getReadableDatabase();
// Writeable:
SQLiteDatabase db = db_con.getWritableDatabase();
A tutorial on how to use the SQLiteOpenHelper can be found here.
The best you could do is to have a database helper where you could have all these calls and which could be available and accessible by all your activities.
Moreover, you should remove and install again your app in order to be able to create the table. I have this problem sometimes.