Get the field value with a Cursor - java

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

Related

Android Studio - SQLite Cursor not returning any data

I am trying to return the names of distinct values in the 'category' column of an SQLite database. The cursor does not appear to be returning any results.
I'm building an Android app using a pre-existing database of bird species. The aim is to allow the user to explore the database through the app. The problem I'm having is in trying to return the distinct categories of bird species that exist in the database. The database appears to be opening successfully - no SQLite exception is being thrown, - but after using the query, the '.moveToNext' method does not appear to be returning any data.
public ArrayList<String> getCategory(String[] name){
String TABLE_BIRDS = "main";
String[] COLUMN = name;
ArrayList<String>categories = new ArrayList<>();
if (name[0]!=null)
{
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
x = db.query(true, TABLE_BIRDS, new String[] { COLUMN[0] } , null, null, COLUMN[0], null, null, null );
if (x.moveToNext()) {
Log.i(LOG_TAG, x.getString(x.getColumnIndex("category")));
}
else {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
//Simple cursor loop
if (x.moveToNext()){
String category = new String();
category = x.getString(x.getColumnIndex(category));
categories.add(category);
Log.i("cursor loop", category);
}
return categories;
In the above code, the log messages are showing that: getCategory is receiving the expected string "category" before the query, but right after the query, the if/else loop is reporting that "The cursor is not returning any data".
What I expected is that the query would return six Strings, the cursor loop would add them to the ArrayList 'categories', and this ArrayList would be returned.
Please any help would be appreciated.
Here is a simpler version of your method:
public ArrayList<String> getCategory(String[] name) {
String TABLE_BIRDS = "main";
ArrayList<String> categories = new ArrayList<>();
if (name[0] != null) {
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
while (x.moveToNext()) {
String category = x.getString(0);
categories.add(category);
Log.i("cursor loop", category);
}
if (x.getCount() == 0) {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
x.close();
return categories;
}
I guess name[0] contains the string 'category' which is the column that you want to query.
Since you pass true as the 1st argument in the method query() this means that you will get distinct values, so no need for the group by argument.
You don't need the variable COLUMN since you have what you need in the variable name.Also you don't need getColumnIndex() since the cursor returns only 1 column.
Edit
Instead of:
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
try rawQuery():
Cursor x = db.rawQuery("SELECT DISTINCT " + name[0] + " FROM " + TABLE_BIRDS, null);
Assuming the cursor is not null, you should
iterate over the results with a while/for loop.
e.g :while(x.moveToNext()) {
//your logic
}
It is always useful when debugging this kind of issues to install an SQLite DB browser then check the cursor's query against your DB to see if you have any data.

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

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!

Android - Fetching only rows with a value in a column in java

First of all, please bear with me, I have minimal experience with SQLite. I am writing an app in Java for the Android platform and I've run into an issue while attempted to query a SQLite database.
I have implemented a database and I am unsure of how to write a method which returns a cursor of only specific rows with a certain value in a certain column. Say there is a column titled "date", I would like to write a method which returns all the columns that do not have the value string "null" in the "date" column.
I know how to write a fetchAll() method and how to write a fetch() for specific rows given an ID, but I not multiple specific rows.
If anyone can help me it would be greatly appreciated.
These will return all the row where Date!=null
public Cursor fetch()
{
return db.query(DATABASE_TABLE,
null,
DATE + "!=''",
null,
null,
null,
null);
}
If you don't need all columns then use
public Cursor fetch()
{
return db.query(DATABASE_TABLE,new String[] {
DATE,
TIME
},
DATE + "!=''",
null,
null,
null,
null);
}
For fetching multiple row using curosor, Have a go with this, You could customize it for your need:
public List<String> getNotNullValues(String value) {
String[] resultCols = new String[] { "Give your result column name here" }; //u could specify multiple column name here
List<String> list = new ArrayList<String>();
int count = 0;
Cursor cr = getWord("DATE", "Your Table Name", "Value of the column",
resultCols,"!="); //Cr is the cursor for resulted query
if (null == cr) {
return null;
}
do {
list.add(cr.getString(0)); //Fill the list or whatever here while traversing with the cursor
} while (cr.moveToNext());
cr.close();
return list;
}
}
public Cursor getWord(String columnName, String tblName, String rowId,
String[] columns, String condition) {
String selection = columnName + condition ; //condtion for selecting a value : "= ?"
String[] selectionArgs = new String[] { rowId };
return query(selection, tblName, selectionArgs, columns);
}
here are the steps:
Form the query with condition, column name and required column name
Get the cursor to the resulting query
Move the cursor to the next record till cr.moveToNext() returns false
For further reference:
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!

Categories