Storing SQL query output in an Array - java

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();

Related

Android SQLite get all rows where column contains string always returns -1

textAs the title describes I'm trying to get all rows from a table where strings of a column contains a string anywhere in it. But they way I'm doing it now always return -1 rows.
This is how i'm doing it now but I have no idea of what I might be doing wrong. Suggestions?
Cursor cursor = database.query(DBHelper.TABLE_RECENT, null, DBHelper.COLUMN_TEXT+ " LIKE '%"+club_id+"%'", null, null, null, null);
Just write cursor.moveToFirst(); before getting data from cursor or just under query line.
Hope it will help you.
I guess, you're mis interpreting the structure of query. the second parameter is what you want to select. such as "select column1, column2 etc. Here's a line from my code, and it works for me.
Cursor cursor = db.query(table_employees, new String[] {KEY_ID, KEY_NAME,KEY_DEPARTMENT, KEY_PHONE_NUMBER, KEY_SALARY}, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
here "new string[] {key_id.....", the second parameter, is column names, that you wanted to select.
OR
alternately, you may simply do as:
String query = "Select * from "+DB_TABLE+ "Where" +column1 + "=" + t +"and"+ column2 + "=" +tt
db.rawQuery(query);
if you do something like,
String query = "Select * FROM Product where name LIKE '%" + Text + "%'"
Log.d("search query", query);
Cursor c = db.rawQuery(query, null);
c.moveToFirst();

SQLitedatabase function of moveToFirst

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!

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