Searching within cursors? - android

In android cursors I want to search within that cursor . i already have my query result in a cursor "c" and want to further search on the same cursor "c" with a like query .Any help would be appreciated
I have 2 cursors say
c1=fetchalldata();
c2=fetchwithcriteria(criteria);
c2 returns a coloumn id ID say at position say P2
I basically want the position of ID in cursor C1 without changing the order of records in c1.

What is your exact problem or query that you want to perform? Instead of going for searching inside a cursor, you should try to write the query that combines your exact query in one cursor itself. So, better would be write a single query with INNER JOIN or fetching Data from Multiple Tables or whatever is your query requirement. Cursor itself is an result/output of a query, so it won't be possible to write a query on a result.

solved Had to use a loop!!
int getPosition(int id){
c.moveToLast();
for(int i=c.getCount();i>0;i--,c.moveToPrevious())
{
if(id==c.getInt(c.getColumnIndexOrThrow(Databaseadapter.KEY_ROWID)))
{
return c.getPosition();
}
}
return 0;
}

Related

Moving android sql lite cursor forward

I have a Sql lite table in my application.
I want to add a cursor to parse the table such that it moves ahead from the current position.
Main idea is to update all next rows and not previous one.
can anyone give me a example cursor to do so with any loops if required ?
if (cursor.moveToFirst()) { //Replace this with cursor.moveToPosition(position) to iterate from that position to the end of your cursor, rather than from start to finish.
while (!cursor.isAfterLast()){
cursor.getInt(0); //get whatever information you require.
cursor.moveToNext();
}
if (!cursor.isClosed()) {
cursor.close();
}
}
There are many ways to achieve this. In the above example, I first check to ensure that the cursor isn't empty, and then go through each row one by one until I reach the final row. When done, I call close() on the cursor.

How To Use SQLite COUNT in Android to return number of rows

I want to write a query that add up all the rows that have the string value of "left" in column named DIRECTION. Next I want to return this sum.
In my code snip-it below assume data and data base are established.
Here is the prototype:
public int getSumLeft() {
String selectQuery = "SELECT COUNT( "+TableData.TableInfo.DIRECTION+" ) WHERE "+TableData.TableInfo.DIRECTION+" = left";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
int sum = cursor.getInt(0);
cursor.close();
return sum;
}
I've tried several queries and this one seems to be the closes to what I need. I think the problem is with statement 'int sum = cursor.getInt(0);'
I think the zero parameter is overriding the results. When I remove the zero the code breaks. getInt is an SQLite function that is used to access data in the database. I did not create that function. But I must use it or and another function like it.
Also, do I need to put a while loop around the query to move the cursor for a COUNT query? Doesn't the Database count for you, therefor no need for iteration?
Is there another way of counting the rows where the string value is 'left' and the sum can be returned?
Full code here:
Database:
https://github.com/Leoa/Accelerometer/tree/AccelerometerDEV/app/src/main/java/thedatabase
Implementation (see the button in onCreate function ):
https://github.com/Leoa/Accelerometer/blob/AccelerometerDEV/app/src/main/java/com/leobee/accelerometer/MainActivity.java
Thanks for looking into this.
I think the zero parameter is overriding the results
I have no idea what you think that this means.
When I remove the zero the code breaks
That is because getInt() needs to know the column of the Cursor to retrieve.
You are also crashing at runtime, as your SQL is invalid. Your SQL statement amounts to:
SELECT COUNT(foo) WHERE foo = left
(where foo is whatever TableData.TableInfo.DIRECTION in Java refers to)
Not only does your SQL statement lack a table to query against, but if left is supposed to be the value of a string column, you need to quote it. You will wind up with something like:
SELECT COUNT(foo) FROM tablename WHERE foo = 'left'
do I need to put a while loop around the query to move the cursor for a COUNT query?
No.
Is there another way of counting the rows where the string value is 'left' and the sum can be returned?
Not really, other than the fix that I outline above.
I think the problem is you need to add quotes on the 'left'
String selectQuery = "SELECT COUNT( "+TableData.TableInfo.DIRECTION+" ) WHERE "+TableData.TableInfo.DIRECTION+" = 'left'"

android sqlite cursor crashes the app

Hello Stackoverflow members!
There is a strange problem in my app. When there is a few db rows (more than 0) in the table, the query works good. when there is no rows in the table, the app crashes ,and then, if I remove these lines, the app works ok:
Cursor result = db.rawQuery("Select * from users ORDER BY `ID` DESC" ,null);
result.moveToFirst();
String lastuser = result.getString(resultSet2.getColumnIndex("username"));
I hope you can help me =]
It looks like the crash is caused by the result not having any rows. You can check how many rows you obtained by using the getCount method on your cursor. If it's zero, do not try to get results from an empty set.
You can read more about cursors here.
After making your query, the cursor will be before the first position. So you have to move it to the first position, as you already do it with result.moveToFirst(). However, if your result was empty, the there is no first position and you get an Exception.
What you could do is either test
if(result.moveToFirst()){
// here you can access the content
}
or you try it with a loop (that way you can also react on results with multiple rows)
while(result.moveToNext()){
String lastuser = result.getString(resultSet2.getColumnIndex("username"));
// here you can access ALL row entries one after another, or just the one row
}
Here is a clear tutorial on using SQLite – hope it helps
First change your query as(remove single quote from ID )
Cursor result = db.rawQuery("Select * from users ORDER BY ID DESC" ,null);
And as #Gooey suggest You can check how many rows you obtained by using the getCount.
So use
Cursor result = db.rawQuery("Select * from users ORDER BY ID DESC" ,null);
if ((result != null) && (result.getCount() > 0)) {
result.moveToFirst();
String lastuser = result.getString(resultSet2.getColumnIndex("username"));
}
And post logcat exception,if still problem occur.

Imported sqlite database is missing data and mixing columns

I have put an sqlite database in my assets folder and imported it onto the phone.
I created an object with multiple properties and when I create a list of that object and assign each property a value from a column of the table they get mixed up
Below is my code
public ArrayList<Exercise> getExercisesFromQuery(String Query) {
ArrayList<Exercise> ExerciseList = new ArrayList<Exercise>();
Cursor cursor = mDb.rawQuery(Query, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Exercise e = new Exercise();
e.setID(Integer.parseInt(cursor.getString(0)));
e.setName(cursor.getString(1));
e.setMuscle(cursor.getString(2));
e.setDescription(cursor.getString(3));
e.setFilepath(cursor.getString(4));
e.setSets(cursor.getString(5));
e.setReps(cursor.getString(6));
e.setEquipment(cursor.getString(7));
e.setPrimaryMuscle(cursor.getString(8));
e.setSecondaryMuscle(cursor.getString(9));
e.setDifficulty(cursor.getString(10));
// Adding contact to list
ExerciseList.add(e);
} while (cursor.moveToNext());
}
return ExerciseList;
}
The current problem is when I do object.getName it gives me the muscle and if I do object.getmuscle it is blank and there is no value but if I do object.getDescription it works fine.
It is not a problem with the database it works fine in any sqlite manager.
Any ideas as to what is wrong?
The reason why the columns are not being returned in the order you expect is not clear. They should come back in the order specified in your query or in the order they are on the table if you are doing SELECT *. However it is not really necessary to address that specific puzzle.
A more defensive and maintainable coding approach is to request each column's index from the cursor by using the getColumnIndexOrThrow method instead of hardcoding them. For example:
int ID_INDEX = cursor.getColumnIndexOrThrow("_id");
int NAME_INDEX = cursor.getColumnIndexOrThrow("name");
If the column doesn't exist you'll get an exception. If it does, you now have its index within the cursor which you can use in the calls to cursor.getString:
e.setID(Integer.parseInt(cursor.getString(ID_INDEX)));
e.setName(cursor.getString(NAME_INDEX));
So you no longer need to worry about what order the columns come back in and you won't need to change any hardcoded index values if your query changes in the future.
Make sure that the columns in the database are in the correct order - column Name should be the second column, column Muscle should be the third column.

How to go through every record in SQLite db?

I think it's kinda easy one but still I'm new to android programming so please have patience. I want to know how can I get the number of records (rows) in a specific table in my db. I need this so I can create a loop to go through every record and add each one of it to the specific Array and display it later on. This is the source:
db.openDataBase(); // open connection with db
Cursor c = db.getTitle(5); // loop here through db, right now I'm fetching only one record
startManagingCursor(c);
//adding areas to the list here
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
db.close();
Does anyone can help me with this please? Thx in advance!
SELECT COUNT(*) FROM tablename
To get the number of rows in the cursor, use getCount.
To get the amount of total rows in a table, either use reinierposts solution, or do a select which select all rows in the table and get the count from the cursor. I'm guessing his solution is quicker though unless you actually need all the rows in the table.
Such a query would be:
SELECT * FROM footable;
You don't really need to get a count of how many first; instead, create a db.getTitles() function that returns all of the rows and returns a Cursor, then loop over the Cursor. Right now you probably have a query that looks something like SELECT ColumnA, ColumnB FROM Titles WHERE id = 5; just copy the function, remove the parameter and take off the WHERE clause so it looks like just SELECT ColumnA, ColumnB FROM Titles.
Then your code would look something like this:
db.openDataBase(); // open connection with db
Cursor c = db.getTitles();
startManagingCursor(c);
//adding areas to the list here
if (c != null && c.moveToFirst()) {
do {
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
} while (c.next());
}
db.close();
We check if the function returned a cursor at all, then move to the beginning of the cursor and start looping, going to the next item each time through. For more information on the Cursor interface see the API here, or to learn more about database access and related design practices better in general I suggest going through the Notepad tutorial.

Categories

Resources