Retrieving values using WHERE Clause in SQLite Database table using android - android

I'm trying to fetch value from distance column where name matches the providing string. See the code below :
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
cursor.moveToFirst();
while(cursor.moveToNext()){
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
I'm using an external Database file in assets folder of android and used pretty much same function to populate my spinner.
It is working fine with the spinner but returning the null value when using the above function.
This is my table :
Help me figure out the issue.
Thanks in advance.

//Once try this. It will definitely work.
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
if (cursor.moveToFirst())
{
distance = cursor.getString(0);
}
cursor.close();
return distance;
}
// See here for what's wrong in your code.
// cursor.moveToFirst() to move cursor to first index of cursor.
// cursor.moveToNext() to move cursor to next index.
// See what you did here.
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
cursor.moveToFirst(); // CURSOR INDEX = 0
while(cursor.moveToNext()){ // CURSOR INDEX = 1
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}

There was a problem with the iteration I was performing
The working code is below:
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data WHERE name =? ", new String[] {station_name} );
cursor.moveToFirst();
while(!cursor.isAfterLast()){
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}

public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ",
new String[] {station_name} );
if(cursor.length() > 0){
cursor.moveToFirst();
distance = cursor.getString(0);
}
cursor.close();
return distance;

Related

Index 0 requested with size of 0

I am trying to pull a record from the database but I am getting an error.
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
The following is the code I am using to pull the record.
public String[] getSingleTransaction(String table, String id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = null;
String[] data = new String[4];
try{
cursor = db.query(table, new String[] {KEY_ID, KEY_CREDIT, KEY_DEBIT, KEY_MEMO, KEY_TIMESTAMP}, KEY_ID + "=?",
new String[] {String.valueOf(id)}, null, null, null, null);
if(cursor != null) {
cursor.moveToFirst();
data[0] = cursor.getString(0); //This is where I am getting the error.
data[1] = cursor.getString(1);
data[2] = cursor.getString(2);
data[3] = cursor.getString(3);
data[4] = cursor.getString(4);
}
return data;
}finally {
cursor.close();
}
}
Is anyone able to see what I might be doing wrong here?
First thing i noticed is that you are accessing 5 elements..but your array was declared with 4. Your array must have 5 elements (size 5)..so it will be declared like this:
String[] data = new String[5];
then before accessing the cursor, you have to check if it 'successfully' moved to the first position..with this:
boolean success = cursor.moveToFirst();
if it is 'TRUE' then you can access the cursor. In your case, it would return 'FALSE' if your query would lead to no results..EMPTY result.
Change this:
if(cursor != null) {
cursor.moveToFirst();
data[0] = cursor.getString(0); //This is where I am getting the error.
data[1] = cursor.getString(1);
data[2] = cursor.getString(2);
data[3] = cursor.getString(3);
data[4] = cursor.getString(4);
}
to this:
if(cursor != null) {
if(cursor.moveToFirst()) {
data[0] = cursor.getString(0); //This is where I am getting the error.
data[1] = cursor.getString(1);
data[2] = cursor.getString(2);
data[3] = cursor.getString(3);
data[4] = cursor.getString(4);
}
}
I think the problem is that your cursor is not null but is not returning values, that is why it crashes.
PD: You should increase your String array as the other answer says :) as the following:
String[] data = new String[5];

How to display music name by playlist name Android programming

There are some similar questions have been posted here, I have used those suggestions and tried it in different ways, but still no results for getting out, my codes is like this:
private Cursor getPlaylists(String playlistName) {
Cursor cursor = null;
String[] projection1 = { MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME };
cursor = this.managedQuery(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection1,
MediaStore.Audio.Playlists.NAME + "=\"" + playlistName + "\"", null,
null); // I need to put "" for the string, otherwise sqlite errors for no such table
startManagingCursor(cursor);
cursor.moveToFirst();
String playlist_id = cursor.getString(0);
Long playlist_id2 = cursor.getLong(0);
if (playlist_id2 > 0) {
String[] projection = {
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Playlists.Members.ARTIST,
MediaStore.Audio.Playlists.Members.TITLE,
MediaStore.Audio.Playlists.Members._ID
};
cursor = getContentResolver().query(MediaStore.Audio.Playlists.Members.getContentUri("external",playlist_id2),
projection,
null,
null,
null);
}
return cursor;
But after these codes, how can I exactly get music list names? does then store in projection, but my projection variable are always no music list information inside. If I need to iterate this cursor again to get music list names, how can I do it, I have tried this way.. but it won't work.
// startManagingCursor(cursor);
for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor
.moveToNext()) {
String musicName = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Playlists.Members.TITLE));
Log.i(LOGGING_TAG, musicName);
}
it looks like hasItem is null as always. I am stuck on this for couple of hours, maybe that is a stupid question but any suggestions would be graceful.
If I understand you correctly, you want to list the tracks on a given playlist.
This is how I do it. Once you have your cursor, you just loop around it by getting the values you need.
see examples below :
public Cursor getPlaylistTracks(Context context, Long playlist_id) {
Uri newuri = MediaStore.Audio.Playlists.Members.getContentUri("external",playlist_id);
ContentResolver resolver = context.getContentResolver();
String _id = MediaStore.Audio.Playlists.Members._ID;
String audio_id = MediaStore.Audio.Playlists.Members.AUDIO_ID;
String artist = MediaStore.Audio.Playlists.Members.ARTIST;
String album = MediaStore.Audio.Playlists.Members.ALBUM;
String title = MediaStore.Audio.Playlists.Members.TITLE;
String duration = MediaStore.Audio.Playlists.Members.DURATION;
String location = MediaStore.Audio.Playlists.Members.DATA;
String composer = MediaStore.Audio.Playlists.Members.COMPOSER;
String playorder = MediaStore.Audio.Playlists.Members.PLAY_ORDER;
String date_modified = MediaStore.Audio.Playlists.Members.DATE_MODIFIED;
String[] columns = { _id, audio_id, artist, album, title, duration,
location, date_modified, playorder, composer };
Cursor cursor = resolver.query(newuri, columns, null, null, null);
return cursor;
}
if (cursor!= null){
cursor.moveToFirst();
int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST);
int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.DURATION);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
artist = cursor.getString(artistColumn);
duration = duration + cursor.getLong(durationColumn);
// do something else
}
cursor.close();
}

How to get the first column data in sqlite database?

I am trying to get the first column like below sql but my code show error.
SELECT subject FROM setting WHERE rowid=1
public void getSetting(){
result = "";
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor c = db.query(true, "setting", new String[] {"subject", "language", "selection"}, "row=1", null, null, null, null, null);
for(c.moveToFirst();!(c.isAfterLast());c.moveToNext()){
result = result + c.getString(0);
result = result + c.getString(0);
result = result + c.getString(0);
}
if (c.getCount() == 0)
result = result + "result not found";
c.close();
db.close();
myDbHelper.close();
}
Your stuff is a little hard to understand, but i think i have an idea what you want. You what to get a cursor to return only one row where the row's id is a specific value. And you only want the string from one column of that returned row. I assume that the primary issue is your designation of the _id column that you're looking for. You either called it row or rowid, you gotta double-check that.
Moreover, i hope the following re-write clears up further issues that you might have.
public String getSetting() {
String result = "";
String[] columns = {"subject"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor c = db.query(true, "setting", columns, "rowid = ?", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
myDbHelper.close();
return result;
}
Moreover, moreover. If you get an error you should post it so that we have an idea what's going on.

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

cursor index out of bounds "index 0 requested: with size 0"

I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.
i send in a phone number
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}
query
public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();
return cur;
}
test search
from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}
if number is not found it should do the else statement but it does not get that far
Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + number + "'",null,null,null,null);
String test = null;
if(curs.moveToFirst()) { //edit
test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
}
curs.close();
db.close();
return test; // this will be null if the cursor is empty
}
And get rid of the getIdFromPhone() method.
While you retrive value you have to use cursor.moveToNext;
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}

Categories

Resources