SQLitedatabase function of moveToFirst - java

I have inserted some values in database and queried a cursor using the insertId for data set which I got from the database.insert command but I am not getting what is the function of cursor.moveToFirst(), Why I have to call it ? and after calling it I am able to get the inserted values in some object !!
long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Message newMessage = cursorToMessage(cursor);
cursor.close();

a cursor points to your data. At first it points nowhere, so thats why you have to call moveToFirst(). If you would get more than one result you could call moveToNext() in a while loop and as long as there are results the loop goes on.

This is one way to iterate through all the possible values that a cursor might content each step is being explained:
Cursor cursor = //Reference to whatever cursor you have...
if(cursor != null && !cursor.isAfterLast() && !cursor.isClosed()){
//this method positions the cursor always in the first item, since there's not warranty is pointing to it...
cursor.moveToFirst();
do{
//Here you have the chance to create your transfer data object and populat it with the column values...
String column = cursor.getString(cursor.getColumnIndex("columnName"));
}
//Here we go to the next element in cursor IF any...
while(cursor.moveToNext());
cursor.close();
}
Hope this helps.
Regards!

Related

Save email from first table to second table

I am creating an application. I need the email of the existing user, which is already saved in the first table, and save it into the second table. Which queries or functions do I need to achieve this? Any suggestions?
First, you need to fetch the user's email by passing on the valid row id:
public Cursor getRecord(long id) throws SQLException {
Cursor cursor = this.database.query(true, databaseTable, new String[] {columnId, columnName, columnEmail}, columnId + "=" + id, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Please note, you may have different columns so change the String[] array with your designated columns. Now, we can create another function to save that email in another table like so:
public long insertExistingUser(String name, String email) {
ContentValues contentValues = new ContentValues();
contentValues.put(columnName, name);
contentValues.put(columnEmail, email);
return this.database.insert(otherDatabaseTable, null, contentValues);
}
This will insert the other user's information into the other table. In order for this to work in your application:
DatabaseAdapter db = new DatabaseAdapter(this);
db.open();
Cursor cursor = db.getRecord(current_user_id);
if (db.insertExistingUser(cursor.getString(1), cursor.getString(2)) > 0)
Toast.makeText(this, "Old user's info was inserted!", Toast.LENGTH_SHORT).show();
db.close();
The cursor.getString(1) requires a number that indicates what column it is. Usually, 0 is the id column which you use to get the user's email.

Storing SQL query output in an Array

I'm looking for a way to store the results/output of an SQL Query into an Array. I have a for loop which runs a query and each time the query is ran I would like to store the results in an array/arraylist. I tried using a cursor but I cannot store multiple strings in a cursor.
Here is the for loop:
for (int i=1;i<code.length;i++) {
Cursor cursor = myDataBase.query("codes", new String[]{"description"}, ("code = '" + code[i] + "'"), null, null, null, null);
cursor.moveToFirst();
String temp = cursor.getString(i);
result.add(i, temp);
cursor.close();
This doesn't seem to work.
Any suggestions or examples that could help?
Thanks
Assuming that code is a list of ids and the table name is named codes, and that you would like to retrieve the list of descriptions for all the codesTry you should this (using StringUtils.join from Apache commons):
String codes = StringUtils.join(code,",");
Cursor cursor = myDataBase.rawQuery("select description from codes where code in (?)",new String[]{codes});
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.add(cursor.getString(1));
}
cursor.close();

Adding data from a SQLite column

I'm, trying to add a credit score from multiple records of an SQLite table.
Each record has a column called credit score, I want to add them all together but I'm having trouble.
Here is the code:
String[] projection2 = { BorrowMeTable.COLUMN_CREDIT_SCORE };
Cursor databaseCursor2 = getContentResolver().query(uri, projection2,
null, null, null);
int number = 0;
if (databaseCursor2 != null) {
databaseCursor2.moveToFirst();
while (databaseCursor2.moveToNext()) {
number = number + databaseCursor2.getInt(
databaseCursor2.getColumnIndexOrThrow(
BorrowMeTable.COLUMN_CREDIT_SCORE));
}
}
Log.d("SCORE", Integer.toString(number));
The problem is the while statement, when it is in place it doesn't pull any data. When I remove it, it pulls the correct data but only from one record.
Use the sum funstion in SQLite
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(COLUMN_CREDIT_SCORE) FROM BorrowMeTable", null);
You can URI match this in your ContentProvider as a different URI
Then simply get the scalar value:
if(cursor.moveToFirst()) {
return cursor.getInt(0);
Use do->while to start from first record
do{
number = number + databaseCursor2.getInt(
databaseCursor2.getColumnIndexOrThrow(
BorrowMeTable.COLUMN_CREDIT_SCORE));
}while (databaseCursor2.moveToNext());

How to get highest row number using query?

I have an sqlitedb, row _id auto increments. How do I form a query to get the highest number in row _id and put that into a variable? I know how to do it in sql but not using the query method.
As answered elsewhere on this site:
String query = "SELECT MAX(row_id) AS max_id FROM mytable";
Cursor cursor = db.rawQuery(query, null);
int id = 0;
if (cursor.moveToFirst())
{
id = cursor.getInt(0);
}
Cursor Days = db.query(true, DATABASE_TABLE, new String[]{"_id"},
"_id="+"(select max(_id) from" +DATABASE_TABLE+")" , null, null, null, null, null);
This should also work.
cursor.getLong(cursor.getColumnIndex("row_id"))
Did you try this? When you insert the data in database, autoincrement increases the id for primary key and I assume row_id must be your one of the keys.
you can get this by count and also by using MAX(column name) function in your query.
max function returns the maximum value
Cursor newCursor = newContentResolver.query
(
CONTENT_URI,
new String[]{"_id"},
null,
null,
null
);
if(newCursor.moveToLast())
{
int index = newCursor.getColumnIndex("_id");
String id = newCursor.getString(index);
Log.v("TAG", "Highest id : "+id);
}
This is one way of getting the highest row id. Since the generation is auto increment, we are assured that the last row is the highest in the database. moveToLast() moves the cursor to the last row.

Get the field value with a Cursor

I'm creating an application and I have problems with Cursor. I have an SQLiteDatabase that returns me a Cursor when I try to fetch the values with this function:
public Cursor fetchOption(long rowId) throws SQLException {
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I don't know how to obtain the value of the field in the Cursor. If I do that like so:
String a = mOptionDb.fetchOption(0).getColumnName(0).toString();
String b = mOptionDb.fetchOption(0).getColumnName(1).toString();
String c = mOptionDb.fetchOption(0).getColumnName(2).toString();
I only obtain the name of the columns (_id, title, body) but not the values. Any suggestions on how to achieve this?
I think you can forget about checking for null.
Instead check if there is data and then access the columns using the cursor:
Cursor cursor = fetchOption(0);
if (cursor.moveToFirst()) // data?
System.out.println(cursor.getString(cursor.getColumnIndex("title"));
cursor.close(); // that's important too, otherwise you're gonna leak cursors
It might also make sense to read an Android tutorial. The notepad tutorial seems to fit the bill: http://developer.android.com/guide/tutorials/notepad/index.html
You can use the Cursor's get* methods to retrieve values from the result:
long id = cursor.getLong(cursor.getColumnIndex("_id"));
long title = cursor.getString(cursor.getColumnIndex("title"));
...
Better practice is obviously to use constants (often provided by ContentProviders) instead of calls to getColumnIndex with hardcoded strings.
You can use this mechanism.
Cursor record=db.test(finalDate);
if(record.getCount()!=0){
if(record.moveToFirst()){
do{
Imgid1=record.getString(record.getColumnIndex(Database.PHOTO));
}while(record.moveToNext());
}
record.close();
}

Categories