Cursor moveToPosition - android

I wish to pull out of the second row of the column NAME.
case R.id.buttonTest: {
String[] projection = {DbTest.NAME};
String selection = "_id = ?";
String[] selectionArgs = { String.valueOf(1) };
Cursor c = sqdb.query(DbTest.TABLE_NAME,projection,selection,selectionArgs ,null,null,null);
moveToPosition(2);
String name = c.getString(c.getColumnIndex(DbTest.NAME));
textView1.setText(name);
}
break;

Call moveToPosition on reference to cursor:
c.moveToPosition(int)

If you`ll call
cursor.moveToFirst();
then after
cursor.moveToNext();
, you will move to the second position.

I used this in my code,
while (cursor.moveToNext()){
if(cursor.getPosition() == position){
String sss = cursor.getString(0).toString();
}
}

Related

Cursor, Sqlite. How do I get the row for ID?

How do I get the row for ID ?
I try so it is impossible .
case R.id.buttonTest: {
String[] projection = {DbTest.NAME};
String selection = "_id = ?";
String[] selectionArgs = { String.valueOf(1) };
Cursor c = sqdb.query(DbTest.TABLE_NAME,projection,selection,selectionArgs ,null,null,null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(DbTest.NAME));
textView1.setText(name);
}
}
break;

Sqlite, How to check if a row contains either string

Using the code below i can check if a row contains a single string ( String a) but how would i check if a row equals either string (String a or b)?
public Cursor fetchMyList() {
String[] columns = { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY,
KEY_DESCRIPTION, KEY_EMAIL };
String selection = "description=?";
String a = "blue";
String b = "red";
String[] selectionArgs = { a };
// String[] selectionArgs = { a , b}; ///tried this dont work!!
Cursor cursor = null;
try {
cursor = database.query(DATABASE_TABLE, columns, selection,
selectionArgs, null, null, null);
} catch (Exception e) {
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if (numberOfRows <= 0) {
return cursor;
}
return cursor;
}
You can only pass 2 arguments if you declare 2 arguments. This is what you want:
String selection = "description=? OR description=?"; // Select rows with either description
String[] selectionArgs = {a , b};
I strongly suggest you check SQL language.
PS: do not catch Exception. You'll regret it later. Catch specifc Exception children; in your case you want to catch SQLException.
PS2: use Log instead of printStackTrace().

rawQuery(query, selectionArgs)

I want to use select query for retrieving data from table. I have found, rawQuery(query, selectionArgs) method of SQLiteDatabase class to retrieve data. But I don't know how the query and selectionArgs should be passed to rawQuery method?
rawQuery("SELECT id, name FROM people WHERE name = ? AND id = ?", new String[] {"David", "2"});
You pass a string array with an equal number of elements as you have "?"
Maybe this can help you
Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i] = c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
One example of rawQuery - db.rawQuery("select * from table where column = ?",new String[]{"data"});
if your SQL query is this
SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'
then rawQuery will be
String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"}
db.rawQuery(query, selectionArgs);
see below code it may help you.
String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);
or
String q = "SELECT * FROM customer WHERE _id = " + customerDbId ;
Cursor mCursor = mDb.rawQuery(q, null);
For completeness and correct resource management:
ICursor cursor = null;
try
{
cursor = db.RawQuery("SELECT * FROM " + RECORDS_TABLE + " WHERE " + RECORD_ID + "=?", new String[] { id + "" });
if (cursor.Count > 0)
{
cursor.MoveToFirst();
}
return GetRecordFromCursor(cursor); // Copy cursor props to custom obj
}
finally // IMPORTANT !!! Ensure cursor is not left hanging around ...
{
if(cursor != null)
cursor.Close();
}
String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
String name= mCur.getString(mCur.getColumnIndex("Name"));
String family= mCur.getString(mCur.getColumnIndex("Family"));
mCur.moveToNext();
}
Name and family are your result

Bind or column index out of range, querying sqlite android table Error

I am trying to make a query to sqlite android to see for example how many users of a given username exist in a table.
This is my function. I must specify that "getContentResolver() != null" and so is variable name.
private int findSelectedUser(String name) {
int count = 0;
try {
String[] whereArgs = new String[] {name};
String[] PROJECTION = new String[] { MyProvider.SETTINGS_USERNAME };
Cursor c = getContentResolver().query(MyProvider.SETTINGS_URI,
PROJECTION, MyProvider.SETTINGS_USERNAME , whereArgs, null);
if (c != null) {
count = c.getCount();
c.close();
}
} catch (NullPointerException e) {
}
System.out.println("Found something? " + count);
return count;
}
And after running i receive the error from the subject...and don't get it. In my where clause i have one column, in my where arguments one value.
Please help me make some sence of this, Thank you.
I guess that works:
String[] whereArgs = new String[] {name};
String[] PROJECTION = new String[] { MyProvider.SETTINGS_USERNAME };
Cursor c = getContentResolver().query(MyProvider.SETTINGS_URI,
PROJECTION, MyProvider.SETTINGS_USERNAME + "=?" , whereArgs, null);
if (c != null) {
count = c.getCount();
c.close();
}
If you want to use whereArgs you have to have the same amount of ? in the where as you have items whereArgs
whereArgs will replace the ? in the final database query
String where = "name = ? OR name = ?";
String[] whereArgs = new String[] {
"Peter",
"Jim"
};
that results in name = 'Peter' OR name = 'Jim' for the query.
Btw: don't catch(NullPointerException e) - make your code safe so they can't happen

Iterate through rows from Sqlite-query

I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.
I use this code to populate the TextViews inside the table rows.
Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);
I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.
How can I iterate through the resulting cursor?
Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:
while (cursor.moveToNext()) {
// Extract data.
}
Reference from SQLiteDatabase.
You can use below code to go through cursor and store them in string array and after you can set them in four textview
String array[] = new String[cursor.getCount()];
i = 0;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
array[i] = cursor.getString(0);
i++;
cursor.moveToNext();
}
for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
// use cursor to work with current item
}
Iteration can be done in the following manner:
Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Found a very simple way to iterate over a cursor
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
// access the curosr
DatabaseUtils.dumpCurrentRowToString(cursor);
final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
}
I agree to chiranjib, my code is as follow:
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
do{
//do logic with cursor.
}while(cursor.moveToNext());
}
public void SQLfunction() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"column1","column2" ...};
String sqlTable = "TableName";
String selection = "column1= ?"; //optional
String[] selectionArgs = {Value}; //optional
qb.setTables(sqlTable);
final Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null);
if(c !=null && c.moveToFirst()){
do {
//do operations
// example : abcField.setText(c.getString(c.getColumnIndex("ColumnName")))
}
while (c.moveToNext());
}
}
NOTE: to use SQLiteQueryBuilder() you need to add
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
in your grade file

Categories

Resources