How to go through every record in SQLite db? - android

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.

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.

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.

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.

Android how to query huge database in android (cursor size is limited to 1MB)

I'm working to develop an application that has to query at some time, a database with over 4k rows, and each row has 90 fields (Strings). The problem is that if I select * from database, my cursor gets really big (over 4MB). And the cursor in android is limited to 1MB.
How can I solve this, or what's the most elegant method to workaround this?
It is possible to split database in smaller chunks and query them out?
I found a way to handle this and I want to share with all who need it.
int limit = 0;
while (limit + 100 < numberOfRows) {
//Compose the statement
String statement = "SELECT * FROM Table ORDER someField LIMIT '"+ limit+"', 100";
//Execute the query
Cursor cursor = myDataBase.rawQuery(statement, null);
while (cursor.moveToNext()) {
Product product = new Product();
product.setAllValuesFromCursor(cursor);
productsArrayList.add(product);
}
cursor.close();
limit += 100;
}
//Compose the statement
String statement = "SELECT * FROM Table ORDER someField LIMIT '"+ (numberOfRows - limit)+"', 100";
//Execute the query
Cursor cursor = myDataBase.rawQuery(statement, null);
while (cursor.moveToNext()) {
Product product = new Product();
product.setAllValuesFromCursor(cursor);
productsArrayList.add(product);
}
cursor.close();
The main idea is to split your data, so you can use the cursor as it should be used. It's working under 2 s for 5k rows if you have indexed table.
Thanks,
Arkde
Well as a rule you never do select *. For a start each row will have a unique identifier, and your user will want to select only certain rows and columns - ie what they can see on an android screen. Without appearing to be rude this is a pretty basic question. You only return the columns and rows you want to display for that screen on the phone - otherwise you consume unnecssary battery life transfering never to be diaplayed data. the standard approach is to used parameterised stored procedures. Google parameterised stored procedures and do a little reading - by the by - you cant update any table unlees you return the unique row identifier for that table.
Do you need all these rows at the same time? Can you fetch them in parts? This question has been asked several times: Android SQLite and huge data sets
Here's one more suggestion: If you have 90 fields that you need to modify, split them into 10 different views. On each view have a left arrow and right arrow so you can horizontally traverse across screens. Hence each view will show 9 fields. Or some strategy like that. Essentially these are all the same views except for column names so you shouldn't have to modify much code.

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

Categories

Resources