Reputation: 1
When I try to retrieve a blob from my sqlite database, the cursor is throwing an index outofbounds
exception.
My DataBaseHelper class is:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String Database_Name="images.db";
public static final String Table_Name="imgs";
Bitmap bitmap;
public DataBaseHelper(Context context) {
super(context, Database_Name,null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+Table_Name+"(id integer primary key autoincrement , image blob)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if esists "+Table_Name);
}
public boolean insert(byte[] img)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("image",img);
long insert=db.insert(Table_Name,null,cv);
if(insert==-1)
{
return false;
}
else
{
return true;
}
}
And my Results class:
public class Results extends AppCompatActivity {
ImageView imageView;
DataBaseHelper mDataBaseHelper;
Bitmap img;
Bitmap bitmap;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
textView=(TextView)findViewById(R.id.textView3);
mDataBaseHelper=new DataBaseHelper(this);
SQLiteDatabase db=mDataBaseHelper.getReadableDatabase();
Toast.makeText(getApplicationContext(),"Emm",Toast.LENGTH_LONG).show();
Cursor cursor=db.rawQuery("select* from "+mDataBaseHelper.Table_Name,null);
byte[] imageArray=cursor.getBlob(3);
bitmap=BitmapFactory.decodeByteArray(imageArray,0,imageArray.length);
imageView.setImageBitmap(bitmap);
}
}
The above results code is throwing cursor index outofbounds exception,index -1 requested with size of 1
.
Upvotes: 0
Views: 26
Reputation: 21
if (cursor.moveToNext()){
cursor.getBlob(cursor.getColumnIndexOrThrow(yourColumnName));
}
In this way you move the cursor on the first row of your returned data set. In any way a space seems to miss in your select statement.
Upvotes: 1
Reputation: 164064
The table mDataBaseHelper.Table_Name
from which you want to fetch the rows,
by executing this statement:
"select * from " + mDataBaseHelper.Table_Name
has only 1 column, but you try to get the 4th by:
byte[] imageArray=cursor.getBlob(3);
The CREATE
statement in the SQLiteOpenHelper
class shows that there are 2 columns in the table: id
and image
, so you should do:
if (cursor.moveToFirst()) {
byte[] imageArray=cursor.getBlob(1);
}
cursor.close();
try it, but if you get the same error again, this means that the table existing in the db has only 1 column.
So if the problem persists uninstall the app from the emulator/device so the db will be deleted and run again to recreate the table. Then repopulate the table.
Upvotes: 0