Moving android sql lite cursor forward - android

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.

Related

How to get 5 last record in the sqlite db in android?

Since the db does not have create date and some ordering field (but in my observation the last row is the latest record),
so how can i get the five last record in some condition e.g.
five record that their schoolid == 1?
Thanks
public Cursor select()
{
String orderBy = FIELD_pubKey+" DESC";
Cursor cursor = iReadDatabase.query(TABLE_NAME, null, null, null, null, null, orderBy);
cursor.moveToFirst();
return cursor;
}
There's no such thing as a last record or a first or a 42nd.
Which records appears last in the result of a query is dependent on the query plan, or an Explicit order by if you add one.
Select * From Table Where ...
The rows will be returned in whatever order the engine considers suitable at the time.
If you need them in specific order, then add an order by clause to the query, anything else is asking for it.
Something like
Select * From Table Order by SomeColumn desc limit 5
will do what you require.
Now what column you need to order by I've no idea, but you need one that will do the job, assuming automatic primary key, but note it is possible to mess with that.

How to break cursor processing while cursor object hold first row and move to fetch second row?

As I'm fetching only one column from SqLite database but getting more than 1MB of data in my cursor object and I can't split my database query. Is it possible to break cursor processing as soon as cursor fetches first row and at that particular time I want to hold this cursor object values in another object. After that cursor clear this value and move to next for fetching second row in database, this continues till the end of records ?
What if you do the following? (This is just an idea)
Fetch all rows you need with the id column only (fetch the id instead of the blob column).
Iterate throw that cursor and for each line fetch only one row for the given id with your blob. Then you close that Cursor and you open a new one for the next id row:
//just fetch the ids of the wanted rows
Cursor idCursor = db.query("TABLE_NAME",new String[]{"_id"}, null, null, null,null,null);
Cursor blobCursor;
//for each row (id)
while(idCursor.moveToNext())
{
//fetch one row with the blob of the given id
blobCursor = db.query("TABLE_NAME",new String[]{"image"}, "_id = ?", new String[] {new Long(idCursor.getLong(0)).toString()}, null,null,null);
if(blobCursor.moveToFirst())
{
//get the blob and store it
blobCursor.getBlob(0);
}
blobCursor.close(); //close the cursor (and release resources)
}
idCursor.close();
If you are using Cursor(SQLiteCursor) - there is no way to prevent cursor from "eating memory"(break processing as you says) after you fetched first row.
android.database.sqlite is a java wrapper for sqlite3 library which is written on C.
The fact is that sqlite3 has no function to count how much records statement will produce, so you have to scan whole resultset with help of sqlite3_step function until it returns SQLITE3_DONE. SQLiteCursor is derived from CursorWindow.
CursorWindow (has some native methods) at the moment Cursors getCount() method is called first time - it does two things : calculates count of row and caches these rows.
There is custom port(russian) of sqlite3 for android with functionality you need.
If you can not read russian:
java code
native code
native sources

Android delete row with cursor

I am creating a program in Android, on one of the screens I plan to iterate thought the rows in a database, presenting each row to the user and letting him skip it or delete it.
In Java I could user the ResultSet's deleteRow() method, however android currently has no equivalent method. Or event a method to set a column with a mark for deletion.
Would doing the deletion via the SQLiteDatabase delete or executeSql method would the currently opened cursor remain valid and would the deleted row be removed from it?
If it becomes invalid what advise is there to not have to keep re-querying the database (or at least not recompile the statement each time)?
If the cursor is still valid but not updated, would be the best way to ensure the user cannot return to this row?
Are there any better solutions to this problem?
Just build a list of item IDs to be deleted. Once the user operation is finished, you can delete the whole lot of them in a single step.
You can use MatrixCursor to do this:
newCursor = new MatrixCursor(new String[] {col1, col2, col3}); // col names
mCursor.moveToPosition(-1); // your Cursor
while (mCursor.moveToNext()) {
if (<any condition>) {
newCursor.addRow(indicationNames.rows(mCursor));
}
}
mCursor = newCursor ;
By this way you have your cursor updated without affecting the database.

Searching within cursors?

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;
}

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