Android SQLiteDatabase: Reading one column - android

I have a one row database just for saving app data. My goal is to read one column (one value) from it.
This query returns all the columns in a Cursor:
public Cursor readAll() {
return getReadableDatabase().query(tableName, null, null, null, null, null, null);
}
It returns a Cursor with one row in it, just perfect. However, I don't want to read all columns at once, because it's slow as I have blob's in db too.
Instead, I'd like to read just one column at a time, separately. For example, for a column called "TEXT" it would be this:
public Cursor readText() {
String[] projection = new String[]{"TEXT"};
return getReadableDatabase().query(tableName, projection, null, null, null, null, null);
}
However, this won't work, as I get back a Cursor with zero rows.
So, how to read a specific column from SQLiteBatabase in Android?

public Cursor readText() {
return getReadableDatabase().rawQuery("SELECT colName FROM myTable", new String[] {});
}

Syntax seems to be correct. Check please that you use right name of the column. Showing the table generation code and actual query code could help.

You can use this one also
public Cursor readText() {
return getReadableDatabase().rawQuery("SELECT column_name FROM table_name", null);
}

Related

How do you iterate over a cursor in reverse order

Usually when I iterate over a cursor I use something like the following:
while (cursor.moveToNext()) {
// get stuff from the cursor
}
What's the best way to iterate an Android Cursor? has a nice discussion of the various options. But now I need to go backwards from last to first over the cursor.
So what can I do?
There are at least two options.
First, to specifically answer your question about iterating backwards over the cursor, you could do the following:
for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()) {
// get stuff from the cursor
}
Second, you could populate the cursor in reverse order from sql and then iterate over the cursor in your normal way:
SQLiteDatabase db = myHelper.getWritableDatabase();
String[] columns = { MyDatabaseHelper.TEST_DATE, MyDatabaseHelper.SCORE };
String orderBy = MyDatabaseHelper.TEST_DATE + " DESC"; // This line reverses the order
Cursor cursor = db.query(MyDatabaseHelper.TESTS_TABLE_NAME, columns,
null, null, null, null, orderBy, null);
while (cursor.moveToNext()) {
// get stuff from the cursor
}
cursor.close();
db.close();
You can start the cursor in the last position, and use moveToPrevious() until you've finished.
cursor.moveToLast();
do
{
// Stuff
}
while (cursor.moveToPrevious());

best way to create sort order in the Cursor in android?

Is creating different cursor for creating sort orders and distribute it in an model clases for alternating sorting style in an listview in android good practice?
titleCursor = context.getContentResolver().query(sourceUri, projection,
null, null, orderByTitle);
timeCursor = context.getContentResolver().query(sourceUri, projection,
null, null, orderByTime);
dateCursor = context.getContentResolver().query(sourceUri, projection,
null, null, orderByDate);
and values of its cursor will be destributed to each models to get the cursor for sorting for alternating sorting in listview? is it a good practice?
You don't have to create a new cursor. You can just change the sort value for the query, if all other things remain constant. That's why it's a parameter, so you alter it's value upon execution of the query.
Instead of creating a different cursor for each sort, you could maintain a string value or some integer value and based on the value inside an if condition simply change the sort parameter like:
if(value.equals("time")) {
cursor = context.getContentResolver().query(sourceUri, projection,
null, null, orderByTime);
}else if(value.equals("title")) {
cursor = context.getContentResolver().query(sourceUri, projection,
null, null, orderByTitle);
}
and so on.

Understanding SQLite Cursor Behavior

I'm writing a method to update default settings in a table. The table is very simple: two columns, the first containing labels to indicate the type of setting, the second to store the value of the setting.
At this point in the execution, the table is empty. I'm just setting up the initial value. So, I expect that this cursor will come back empty. But instead, I'm getting an error (shown below). The setting that I am working with is called "lastPlayer" and is supposed to get stored in the "SETTING_COLUMN" in the "SETTINGS_TABLE". Here's the code:
public static void updateSetting(String setting, String newVal) {
String table = "SETTINGS_TABLE";
String[] resultColumn = new String[] {VALUE_COLUMN};
String where = SETTING_COLUMN + "=" + setting;
System.err.println(where);
SQLiteDatabase db = godSimDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(table, resultColumn, where, null, null, null, null);
System.err.println("cursor returned"); //I never see this ouput
\\more
}
sqlite returned: error code = 1, msg = no such column: lastPlayer
Why is it saying that there is no such column lastPlayer? I thought that I was telling the query to look at the column "SETTING_COLUMN" and return the record where that column has a value "lastPlayer". I'm confused. Can somebody straighten me out? I've been looking a this for an hour and I just don't see what I am doing wrong.
Thanks!
You're not properly building/escaping your query. Since the value lastPlayer is not in quotes, your statement is checking for equality of two columns, which is what that error message is saying.
To properly build your query, it's best to not do this manually with String concatenation. Instead, the parameter selectionArgs of SQLiteDatabase.query() is meant to do this.
The parameters in your query should be defined as ? and then filled in based on the selectionArgs. From the docs:
You may include ?s in selection, which will be replaced by the values
from selectionArgs, in order that they appear in the selection. The
values will be bound as Strings.
So, your code would look like this:
String where = SETTING_COLUMN + " = ?";
Cursor cursor = db.query(table, resultColumn, where, new String[] { setting }, null, null, null);

Is returning a cursor to fewer columns of a database more efficient

I have looked for a similar question and haven't been able to find one.
I generally use a separate database class in which i define functions to return cursors.
For example,
public Cursor all(Activity activity) //cursor for Activities
{
String[] from = { _ID, column1, column2, column3, column4};
String order = _ID;
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
Then from the activity i can use-
Cursor cursor = database.all(Activity.this); to get an instance of the cursor.
My question is this, suppose i do not need all the column values but say only the first three, is it worth it in terms of performance to define another function in the database class that returns only the first three column values with the cursor.(especially if i am using the cursor to populate a list)
Just so you know, I came across this question while implementing a custom list adapter where i do not need all the column values to draw the list items.

SQLite table query

I query the table by using this function below
public Cursor getTableInfo() throws SQLException
{
return db.query(TableName, null,
null,
null,
null,
null,
null);
}
I got the error "View Root.handleMessage(Message)line:1704". I could insert the data but can't query the data. I called this function below
Cursor c = db.getTableInfo();
int cRow = c.getCount();
if (cRow == 0)
{
Toast.makeText(NewContact.this,
"No Record",
Toast.LENGTH_LONG).show();
}
In SQLite, is there any case-sensitive in the name of database, table, column?
Please help me.
Your db request looks ok and it should return all records from your table.
So maybe there are just no records in the table?
Also it's unclear whether you have problem with db related stuff or with smth else, because the code provided looks ok.
I would rather evaluate the outcome of c.moveToFirst() instead of c.getCount(). The latter means the cursor iterates over the whole dataset which is a more costly operation.

Categories

Resources