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];
Related
Using the code below i wrote in TextView "textStareLed" first unreaded message. How can write the last message?
I try to use the cursor.moveToPrevious() but didn`t work.
protected void AfisareStareLed() {
TextView view = new TextView(this);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSMSURI, null, null, null, null)
while (cursor.moveToNext()){
if(cursor.getString(2).equals("+4xxxxx") && cursor.getString(8).equals("0")){//cursor.getString(8)==0 <=> "read=0"
TextView textStareLed = (TextView) findViewById(R.id.textStareLed);
textStareLed.setText(cursor.getString(13));
}
}
markMessageRead();//mark all message "read=1"
}
Just add "date desc limit 1"
String msgData = "";
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), new String[] {"body"}, null ,null, "date desc limit 1"); //if you change the 1 to 2 you´ll get the last 2 sms...
cursor.moveToFirst();
do{
for(int idx=0;idx<cursor.getColumnCount();idx++)
{
msgData += cursor.getString(idx);
}
}while(cursor.moveToNext());
textStareLed.setText(msgData);
Hi i had fetched all datas from the database and now i have to filter the data by matching its email id and display the filtered data in the listview but i am facing problem as i am getting the first value repeated again and again. please help me i am new in android and i am stuck on this.
I am also sending my code.
for(int i = 0;i<C_parts.size();i++){
if(C_parts.get(i).email.toString().equals(Global.useremailid.toString()))
Cursor cursor = db.query(TABLE_ACCOUNT, new String[] { ACCT_NAME,
ACCT_HEAD_NAME, OPEN_BAL, EMAIL }, EMAIL + "=?",
new String[] { String.valueOf(Global.useremailid) }, null, null, null,
null);
System.out.println("value of cursor:->"+cursor);
if (cursor != null)
cursor.moveToNext();
String acc_name = cursor.getString(0);
String acc_head_name = cursor.getString(1);
String openbal = cursor.getString(2);
String amail=cursor.getString(3);
System.out.println("bfr accountid:->"+acc_name);
System.out.println("bfr accountname:->"+acc_head_name);
System.out.println("bfr headname:->"+openbal);
C_parts1.add(new Account(acc_name,acc_head_name,openbal, amail));
}
}
c_adapter = new CustomAdapter(this, R.layout.list_item, C_parts1);
if (list1 == null)
list1 = (ListView) findViewById(R.id.lv1);
list1.setAdapter(c_adapter);
registerForContextMenu(list1);
list1.invalidate();
}
Change
for(int i = 0;i<C_parts.size();i++){
if(C_parts.get(i).email.toString().equals(Global.useremailid.toString()))
to
for(int i = 0;i<C_parts.size();i++){
if(C_parts.get(i).email.toString().equals(Global.useremailid.toString())) {
Your Cursor code will be executed only if equals, but the other code will be always executed and since the cursor is the same of the previous iteration it will repeat the same data.
It's because if you don't add { } after a if only the first line will be part of the if.
Same here
if (cursor != null)
cursor.moveToNext();
String acc_name = cursor.getString(0);
String acc_head_name = cursor.getString(1);
String openbal = cursor.getString(2);
String amail=cursor.getString(3);
System.out.println("bfr accountid:->"+acc_name);
System.out.println("bfr accountname:->"+acc_head_name);
System.out.println("bfr headname:->"+openbal);
C_parts1.add(new Account(acc_name,acc_head_name,openbal, amail));
}
add a { after if (cursor != null) and make sure every {} are OK.
while(cursor.moveToNext()){
String acc_name = cursor.getString(0);
String acc_head_name = cursor.getString(1);
String openbal = cursor.getString(2);
String amail=cursor.getString(3);
System.out.println("bfr accountid:->"+acc_name);
System.out.println("bfr accountname:->"+acc_head_name);
System.out.println("bfr headname:->"+openbal);
System.out.println("bfr email:->"+amail);
C_parts1.add(new Account(acc_name,acc_head_name,openbal, amail));
System.out.println("value of c_parts1 on for loop:->"+C_parts1.toString());
}
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();
}
}
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.
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