How to retrieve data from cursor class - android

I need to know how to retrieve data from cursor. I need this because the ringtonemanager returns all the audio files in form of cursor object, I need to know how to retrieve the values.
Anbudan.

Once you have the Cursor object, you can do something like this:
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}
cursor.close();

This looks a bit better:
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
...
}

Salvador's answer will continue to fetch data from the row after the last row because moveToNext() will only return false when the cursor is pointing at the row after the last row. It will continue to iterate even if the cursor is pointing at the last row.
The correct template should be:
if (cursor.moveToFirst()){
while(!cursor.isAfterLast()){
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
cursor.moveToNext();
}
}
cursor.close();

Related

how to retrieve a single row data from cursor android?

I want to retrieve the data from cursor when pressing the button. For the first time I want to show first row data, after pressing button I need to show second row data. How can I achieve this? I have more number of rows in my database.
While I am using following code I am getting last row data.
for(int i=0;i<cursor.getColumnCount();i++){
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
}
For the first timebutton click,
cursor.moveToFirst();
Then keep on using,
cursor.moveToNext()
until end of the row.
To be more specific:
if (cursor.moveToFirst()) {
do {
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
} while(cursor.moveToNext();
}
You forgot to move your cursor to first row. Please try this:
if (cursor.moveToFirst())
{
do
{
String path=cursor.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(cursor.getString(1));
brewerimage.setImageBitmap(bitmap);
} while (cursor.moveToNext());
}
You can take first row of data like this
Replace 0 in
cursor.getString(0);
with your value;
if (cursor.moveToFirst())
{
do
{
String path=cursor.getString(0);
title.setText(path);
} while (cursor.moveToNext());
}
Try this hope it will help you:
try {
if (cursorOne.moveToFirst()) {
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
//no need to look up column index since you already know it due to the projection used
}
} finally {
cursorOne.close();
}
Try this..
if (cursor.getCount() > 0) {
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String path=c.getString(2);
Bitmap bitmap=BitmapFactory.decodeFile(path);
title.setText(c.getString(1));
brewerimage.setImageBitmap(bitmap);
}
}
After read your comments i have one idea. That is leave the query as like now.
Step 1
Save your data in static ArrayList or POJO class
Step 2:
Whenever you want to click button just increase the cont +1 and save it. Use this count as position and easily get values.
You can get particular at the given position as like.
public void getRowAt(int posAt){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+tableName+" LIMIT 1 OFFSET "+posAt, null);
int count = cursor.getCount();
while (cursor.moveToNext()){
// here your can get your row data.
}
cursor.close();
db.close();
}
Are you using database so you getting record from database am i right ?
so you getting record in cursor so from which column you getting data you have to pass that column name in your cursor so you are getting result .
example :
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
myDatarecordModel = new DataRecordModel();
myDatarecordModel.setStrDataRecordingID(cursor.getString(cursor.getColumnIndex(AppStackFields.DATARECORDING_ID)));
} while (cursor.moveToNext());
}
cursor.close();

sqlite cursorindexoutofbound exception

in my android application i used the following function to retrieve the column from the table..the table contains value but it has an exception.
public String[] getactivelist(){
Log.v("ppp","getactivelist");
String[] actname=new String[50];
SQLiteDatabase db = this.getWritableDatabase();
Log.v("ppp","dbcrtd");
Cursor cursor = db.rawQuery("SELECT name FROM activelist ORDER BY time ASC", null);
Log.v("ppp","aftrcurser");
int i=0;
Log.v("ppp crsr",cursor.getString(0));
if (cursor.moveToFirst()) {
do {
actname[i]=cursor.getString(0);
Log.v("ppp crsr",cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return actname;
}
the log cat shows the following error
04-04 01:19:41.170 2581-2601/com.example.pranavtv.loudspeaker V/pppīš• tryandroid.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
In your line
Log.v("ppp crsr", cursor.getString(0));
You try to get a string from the cursor. If there aren't any lines, it should throw the error observed.
You are calling the following line...
Log.v("ppp crsr",cursor.getString(0));
...before you have moved the position of your Cursor using...
if (cursor.moveToFirst()) {
By default, the position of a Cursor is initially set to be -1 which is before the first valid position as the first position which contains data is position 0.
Simply remove that line (the one before the if(...)) and you should be good to go.
On another note, in your do...while loop you are using...
actname[i]=cursor.getString(0);
...but you never increment i. Consequentially you will only ever modify actname[0] regardless of how many results are returned to the Cursor.

How to return all data from one column Android SQL

I have an SQLite Database in my application. It has three columns. being _id, TEXT, and Location. If I want to return all the data from, say, the TEXT column should I use cursor.getColumnIndex(2)? I am obviously new to SQLite. And and all help is appreciated. Thanks everyone!
Yes, friend, you are new.
First off, your database doesn't have three columns, but rather, your table does. Databases have tables, tables of columns (fields) and rows (records).
Secondly, TEXT is not a valid name for a column, as it's a datatype. Let's say you called the three columns id, theText, and location -- then if you selected all three columns to be returned, the second one would be accessible through:
cursor.getString(1); // that's the second column returned
or
cursor.getString(cursor.getColumnIndex( "theText" ) );
However, you can have sqlite do most of the work for you by selecting only the column you're interested in, so then you'd cursor.getString(0) as it's the only column returned.
For more pertinent explanations, please post your code in the question.
simply apply the query of getting all contacts and take an array of string type and then add the required record in that array as shown below
I hope this code help u
in DBHelper getting record of particular column :
public ArrayList<String> getAllCotactsEmail() {
ArrayList<String> arrayList=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
if (res != null)
{
while(res.isAfterLast() == false){
arrayList.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));
Log.d("emailssinlisttt",arrayList.toString());
res.moveToNext();
}}
return arrayList;
}
retrieve :
email=mydb.getAllCotactsEmail();
Log.d("emaillllll",email.toString());
You need to query your Database to get your data. This query will return a Cursor with the column you specified in the query.
To make query, you need to call query() method from ContentResolver. To get your ContentResolver, you can use getContentResolver() from a Context like Activity :
getContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
To understand all parameters, see : ContentResolver
In your case, you want only TEXT column so pass a String array with your TEXT column name for projection parameters.
You want all rows so your selection and selectionArgs parameters must be null.
If you don't care about order, pass null for sortOrder (rows will be sort by ID) :
Cursor c = getContentResolver.query(yourUri, new String[]{"TEXT"}, null, null, null)
This query will return a cursor, to extract your values from the cursor, make a loop like :
if(c.moveToFirst()) {
do {
final String text = c.getString(c.getColumnIndex("TEXT"));
} while (c.moveToNext());
}
Hope this will help you :)

Access a column from database

Now I want to access an entire column from database and then compare it with some text that I have stored...but I am getting no idea on how to do that..So can someone please help me with this...
Entire column? You mean all the values for a given column accross all records?
You should iterate the ResultSet obtained and start comparing the values (for example - if you iterate using "rs" object of ResultSet, you should compare:
String valueFromDB = rs.getString("myColumn");
String someTextStored = .... //the text being stored
if (valueFromDB != null) {
if (someTextStored.equals(valueFromDB) {
//Comparison succeeded - implement some logic here for handling success
}
}
And the above code should be inside a loop code that iterates over the ResultSet and
uses the "next" method to obtain the next record.
Hope this helps you
public ArrayList<String> getValues(){
Cursor cursor = null;
SQLiteDatabase db = getReadableDatabase();
Log.v("done","getting rows ");
cursor = db.rawQuery("SELECT YourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
list_values.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
return list_values;
}
Now you are having all the values of a particular column you can compare it from this array list.

What is The use of moveToFirst () in SQLite Cursors

I am a programming newbie
and I found this piece of code in the internet and it works fine
Cursor c=db.query(DataBase.TB_NAME, new String[] {DataBase.KEY_ROWID,DataBase.KEY_RATE}, DataBase.KEY_ROWID+"= 1", null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
but I am not able to understand the use of the
if(c!=null)
{
c.moveToFirst();
}
part. What does it do exactly , and if I remove the
if(c!=null) { c.moveToFirst(); }
part, the code doesn't work.
The docs for SQLiteDatabase.query() say that the query methods return:
"A Cursor object, which is positioned before the first entry."
Calling moveToFirst() does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty). Note that to guard against an empty return set, the code you posted should be testing the return value (which it is not doing).
Unlike the call to moveToFirst(), the test for if(c!=null) is useless; query() will either return a Cursor object or it will throw an exception. It will never return null.
if (c.moveToFirst()) {
while(!c.isAfterLast()) { // If you use c.moveToNext() here, you will bypass the first row, which is WRONG
...
c.moveToNext();
}
}
Cursor is not a Row of the result of query. Cursor is an object that can iterate on the result rows of your query. Cursor can moves to each row. .moveToFirst() method move it to the first row of result table.
moveToFirst() method moves the cursor to the first row. It allows to perform a test whether the query returned an empty set or not. Here is a sample of its implementation,
if (cursor.getCount() == 0 || !cursor.moveToFirst()) {
return cursor.getLong(cursor.getColumnIndexOrThrow(ID_COLUMN));
cursor.close();
what macio.Jun says is right!
we have code like below:
String sql = "select id,title,url,singer,view,info from cache where id=" + id;
SQLiteDatabase db = getMaintainer().getReadableDatabase();
Cursor query = db.rawQuery(sql, null);
query.moveToFirst();
while(query.moveToNext()){
DBMusicData entity = new DBMusicData();
entity.setId(query.getString(query.getColumnIndex(FIELD_ID)));
entity.setTitle(query.getString(query.getColumnIndex(FIELD_TITLE)));
entity.setSinger(query.getString(query.getColumnIndex(FIELD_SINGER)));
entity.setTitlepic(query.getString(query.getColumnIndex(FIELD_PICURL)));
entity.setInfoUrl(query.getString(query.getColumnIndex(FIELD_INFO)));
entity.setViews(query.getString(query.getColumnIndex(FIELD_VIEW)));
Log.w(tag, "cache:"+ entity.toString());
}
query.close();
query=null;
db.close();
db=null;
If we have only one record in the cache table, query.moveToFirst(); will cause that no record returns.

Categories

Resources