Moving a row in sqlite (Position column) - java

So, I am currently using the DragSortListView with a SQLite database. I want to resort my database whenever im dragging an item of the ListView to a new position. Therefore I wrote a piece of code that should manage it. But if I'm moving something from a position below to a higher one, it is strangely sorted. I already looked on this code for hours and asked some friends, but I never found the solution.
Code
Method in the DatabaseHelper
public void moveValues(int from, int to, String sammlung){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
System.out.println(from + " - " + to);
if(from < to){
//This part is working properly
Cursor cursor = sqLiteDatabase.rawQuery("SELECT ID FROM " + TABLE_NAME + " WHERE POSITION IS " + "\"" + from + "\" AND SAMMLUNG IS " + "\"" + sammlung + "\"", null);
for (int i = from+1; i < to+1; i++){
switchPositionValue(i, i-1);
}
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_5, to);
cursor.moveToFirst();
sqLiteDatabase.update(TABLE_NAME, contentValues, "ID=?", new String[]{cursor.getInt(0)+""});
cursor.close();
}else{
//This is the not working part
Cursor cursor = sqLiteDatabase.rawQuery("SELECT ID FROM " + TABLE_NAME + " WHERE POSITION IS " + "\"" + from + "\" AND SAMMLUNG IS " + "\"" + sammlung + "\"", null);
for (int i = from-1; i > to-1; i--){
switchPositionValue(i, i+1);
}
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_5, to);
cursor.moveToFirst();
System.out.println(cursor.getInt(0));
//The next line destroys it. But I dont know how to fix it or what exactly is not working
sqLiteDatabase.update(TABLE_NAME, contentValues, "ID=?", new String[]{cursor.getInt(0)+""});
cursor.close();
}
}
The parameters are:
from: The position it's taken away from
to: The position it's taken to
sammlung: I saving all the items of different collections in one database. So it's only there to sort out only specific items.
Method to change the value of a row with a specific position
public void switchPositionValue(int before, int after){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_5, after);
sqLiteDatabase.update(TABLE_NAME, contentValues, "POSITION=?", new String[]{before+""});
}
Demonstration
So if you've got any idea why its behaving this strange or do know a better approach to moving a row in a database, I would really appreciate your help.

Android other way SQL one (COLUMN_5 is POSITION column)
public void moveValues(int from, int to) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query =
"WITH p(from_position,to_position,max_position,min_position) AS (" +
"SELECT " +
"?," +
"?," +
"(SELECT max(" + COLUMN_5 + ") FROM " + TABLE_NAME + ")," +
"(SELECT min(" + COLUMN_5 + ") FROM " + TABLE_NAME + ")), " +
"updates AS(" +
"SELECT " + TABLE_NAME + ".id," + COLUMN_5 + " AS current, " + COLUMN_5 + " + 1 AS proposed " +
"FROM " + TABLE_NAME + " " +
"WHERE " + COLUMN_5 + " >= (SELECT to_position FROM p) " +
"AND " + COLUMN_5 + " < (SELECT from_position FROM p) " +
"UNION SELECT " + TABLE_NAME + ".id," + COLUMN_5 + " AS current, " + COLUMN_5 + " -1 AS proposed " +
"FROM " + TABLE_NAME + " " +
"WHERE " + COLUMN_5 + " <= (SELECT to_position FROM p) " +
"AND " + COLUMN_5 + " > (SELECT from_position FROM p) " +
"UNION SELECT " + TABLE_NAME + ".id," + COLUMN_5 + ",(SELECT to_position FROM p) " +
"FROM " + TABLE_NAME + " " +
"WHERE " + COLUMN_5 + " = (SELECT from_position FROM p) " +
"AND (SELECT from_position FROM p) <> (SELECT to_position FROM p)" +
"), " +
"finish_updates AS (" +
"SELECT * FROM updates " +
"WHERE max((SELECT from_position FROM p),(SELECT to_position FROM p)) <= (SELECT max_position FROM p) " +
"AND min((SELECT from_position FROM p),(SELECT to_position FROM p)) >= (SELECT min_position FROM p)" +
")" +
"UPDATE " + TABLE_NAME + " SET " + COLUMN_5 + " = " +
"(" +
" SELECT proposed " +
" FROM finish_updates " +
" WHERE finish_updates.id = " + TABLE_NAME + ".id" +
") " +
"WHERE " + TABLE_NAME + ".id IN " +
"(" +
" SELECT id FROM finish_updates" +
");";
SQLiteStatement stmnt = sqLiteDatabase.compileStatement(query);
stmnt.bindLong(1,from);
stmnt.bindLong(2,to);
stmnt.executeUpdateDelete();
}
fiddle test SQL at

Related

'.', <column alias name>, <compound operator>, AS, BETWEEN, FROM, GROUP, IN, LIMIT, ORDER, WHERE, comma or semicolon expected, got 'SELECT'

Please I need help fixing the error above _ in the title _ appeared in the first SELECT after FROM of this query, all suggestions are welcome so thank you very much.
public ArrayList<HashMap<String, String>> getAll_Datas() {
ArrayList<HashMap<String, String>> arrayListAllData = new
ArrayList<HashMap<String, String>>();
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery
(
" SELECT lespontes.idPontes ,\n" +
" lespontes.Cage as Cage,\n" +
" lespontes.Couvés,\n" +
" dbfécondation.Fécondés " + "FROM " +
(
" SELECT idPontes FROM lespontes"+
" UNION "
+ " SELECT idPontes FROM dbfécondation" ) +
" LEFT OUTER JOIN"
+ " lespontes USING (idPontes)"+
" LEFT OUTER JOIN "
+ " dbfécondation USING (idPontes)"+
" Order By " + " lespontes.Cage " + " ASC ",null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> hashMapData= new HashMap<String,
String>();
hashMapData.put("idPontes", cursor.getString(0));
hashMapData.put("Cage",cursor.getString(1));
hashMapData.put("Couvés",cursor.getString(2));
hashMapData.put("Fécondés", cursor.getString(3));
arrayListAllData.add(hashMapData);
} while (cursor.moveToNext());
}
return arrayListAllData;
}
Try using :-
Cursor cursor = database.rawQuery
(
" SELECT lespontes.idPontes ," +
" lespontes.Cage as Cage," +
" lespontes.Couvés," +
" dbfécondation.Fécondés " + "FROM (" +
" SELECT idPontes FROM lespontes" +
" UNION "
+ " SELECT idPontes FROM dbfécondation)" +
" LEFT OUTER JOIN"
+ " lespontes USING (idPontes)" +
" LEFT OUTER JOIN "
+ " dbfécondation USING (idPontes)" +
" Order By " + " lespontes.Cage " + " ASC ", null);
i.e. the parenthesises surrounding the SELECT have been embedded within the SQL. Also the useless line feeds (\n's) have also been removed.

SQLite query for ordering a list based on mistakes made

I would like to know how to query a database based on the amount of mistakes made by a waiter.
The two tables I have are
Employee
String employeeTable = "CREATE TABLE " + EMP_TABLE + " ("
+ ID_EMP + " INTEGER PRIMARY KEY, "
+ FIRST_NAME + " TEXT,"
+ LAST_NAME + " TEXT,"
+ PROFIT + " INTEGER);";
MistakeEmployee
String mistakeTable = "CREATE TABLE " + MISTAKE_TABLE + " ("
+ ID_MISTAKE + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ID_WAITER_MISTAKE + " INTEGER,"
+ ID_ORDER_MISTAKE + " INTEGER,"
+ MISTAKE_TOTAL + " INITGER,"
+ " FOREIGN KEY (" + ID_WAITER_MISTAKE + ") REFERENCES " + EMP_TABLE + "(" + ID_EMP + "), "
+ " FOREIGN KEY (" + ID_ORDER_MISTAKE + ") REFERENCES " + ORDER_TABLE + "(" + ID_ORDER + "));";
I am trying to order the list based on the Employee with the most Mistakes which would be counted in the mistakes table using the ID_WAITER_MISTAKE.
String query = SELECT * , COUNT(Mistake_TABLE.ID_Waiter) as Count
FROM EMP_TABLE
ORDER BY Count DESC
You must join the tables, group by employee and aggregate:
SELECT e.ID_EMP, e.FIRST_NAME, e.LAST_NAME,
COUNT(m.ID_MISTAKE) AS Mistake_Count
FROM employeeTable e LEFT JOIN mistakeTable m
ON m.ID_WAITER_MISTAKE = e.ID_EMP
GROUP BY e.ID_EMP, e.FIRST_NAME, e.LAST_NAME
ORDER BY Mistake_Count DESC, e.ID_EMP
and in Java code you should construct the sql string like this:
String query =
"SELECT e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + ", " +
"COUNT(m." + ID_MISTAKE + ") AS Mistake_Count " +
"FROM " + EMP_TABLE + "AS e LEFT JOIN " + MISTAKE_TABLE + " AS m " +
"ON m." + m.ID_WAITER_MISTAKE + " = e." + ID_EMP + " " +
"GROUP BY e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + " " +
"ORDER BY Mistake_Count DESC, e." + ID_EMP ;
I hope there are no typos.

Sqlite single column update query is not working

My UpdateRow function is not working. Can someone help?
public boolean UpdateRow(String date ,String timeOut) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "=" + timeOut + "WHERE " + COL_1 + "=" + date);
}
Thanks in advance.
I think the query that you have written is missing a space between WHERE clause and COL_1. The line should be written as follows.
db.execSQL("UPDATE " + TABLE_NAME
+ " SET " + COL_3 + " = " + timeOut
+ " WHERE " + COL_1 + " = " + date
);
Apostrophes around date and space between columns:
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "=" + timeOut + " WHERE " + COL_1 + "='" + date + "'");
If timeOut is TEXT then it needs apostrophes too:
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "='" + timeOut + "' WHERE " + COL_1 + "='" + date + "'");

SQLiteException no such table, am I missing something?

I have researched other instances of this error all morning but nothing i've tried so far has worked. It could be something obvious as I am quite new to this.
I am trying to return the results of the GET_ALL_INGREDIENTS query. Which I will then put into a 2d array, but you don't need to worry about that. My TABLE_RECIPES table works fine.
SQLiteException: no such table: TABLE_INGREDIENTS (code 1): , while compiling: SELECT INGR...etc....
Which occurs on the last line of this bit of code:
public String[][] getRecipeIngredients(int id) {
String GET_ALL_INGREDIENTS = "SELECT INGREDIENT_NAME, INGREDIENT_QUANTITY, INGREDIENT_UNIT " +
"FROM TABLE_INGREDIENTS " +
"INNER JOIN TABLE_RECIPE_INGREDIENTS ON TABLE_RECIPE_INGREDIENTS.INGREDIENT_ID=TABLE_INGREDIENTS.INGREDIENT_ID " +
"WHERE RECIPE_INGREDIENTS.RECIPE_ID=" + id;
db = new MyDBHandler(mContext);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(GET_ALL_INGREDIENTS, null);
Table Creation:
final String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPES + "(" +
RECIPE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RECIPE_NAME + " TEXT, " +
RECIPE_INSTRUCTIONS + " TEXT " +
")";
final String CREATE_TABLE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
TABLE_INGREDIENTS + "(" +
INGREDIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
INGREDIENT_NAME + " TEXT NOT NULL UNIQUE " +
")";
final String CREATE_TABLE_RECIPE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPE_INGREDIENTS + "(" +
RECIPE_ID + " INTEGER NOT NULL, " +
INGREDIENT_ID + " INTEGER NOT NULL, " +
INGREDIENT_QUANTITY + " REAL, " +
INGREDIENT_UNIT + " TEXT, " +
"PRIMARY KEY (" + RECIPE_ID + "," + INGREDIENT_ID + "), " +
"FOREIGN KEY (" + RECIPE_ID + ") REFERENCES " + TABLE_RECIPES + "(" + RECIPE_ID + "), " +
"FOREIGN KEY (" + INGREDIENT_ID + ") REFERENCES " + TABLE_INGREDIENTS + "(" + INGREDIENT_ID + ")" +
")";
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_RECIPES);
db.execSQL(CREATE_TABLE_INGREDIENTS);
db.execSQL(CREATE_TABLE_RECIPE_INGREDIENTS);
}
Thank you for reading and I really appreciate any help i can get with this.
TABLE_INGREDIENTS is a variable. It's value is likely not "TABLE_INGREDIENTS" that is a string literal. So you might want to change
"FROM TABLE_INGREDIENTS " +
to
"FROM " + TABLE_INGREDIENTS +
(You have a number of other similar issues in your SQL too.)

Delete all but top n from database table in SQLite for java/android

I am new in java but I am trying to code:
SQLiteDatabase db = this.getWritableDatabase();
//db.execSQL("delete from " + TABLE_BOOKMARKS + " where " + KEY_ID + " not in (select " + KEY_ID + " from " + TABLE_BOOKMARKS + " order by " + KEY_ID + " limit 10)" );
//db.execSQL("DELETE FROM " + TABLE_BOOKMARKS + " WHERE " + KEY_ID + " NOT IN (SELECT TOP 10 " + KEY_ID + " FROM " + TABLE_BOOKMARKS + ")" );
db.execSQL("Delete From "+TABLE_BOOKMARKS+" where "+ KEY_ID + " not in (Select Top 10 "+ KEY_ID +" from "+ TABLE_BOOKMARKS + " order by " + KEY_ID +")");
db.close(); // Closing database connection
you can see in the code, I have tried in 3 different ways but when I run it my application returns error and stops!
I got this error:
android.database.sqlite.SQLiteException: near "10": syntax error: ,
while compiling: Delete From bookmarks where id not in (Select Top 10
id from bookmarks order by id)
You can try
db.execSQL("Delete From "+TABLE_BOOKMARKS+" where "+ KEY_ID + " not in (Select "+ KEY_ID +" from "+ TABLE_BOOKMARKS + " order by " + KEY_ID +" limit 10)");

Categories