0

I'm trying to get a blob from sqlite to string, please see below:

ArrayList<Sudentdb> list;

GridView gridView;

final String[] from = new String[] { SQLiteHelper._ID,
        SQLiteHelper.NAME, SQLiteHelper.AGE, SQLiteHelper.PROFILE };

final int[] to = new int[] { R.id.rowid, R.id.txtName, R.id.studentage, R.id.profileimageV };

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.studentfragment, null);

    gridView = (GridView) v.findViewById(R.id.gridView);

    DBManager dbManager = new DBManager(getActivity());
    dbManager.open();

    Cursor cursor = dbManager.fetch();

    list = new ArrayList<>();
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.single_item, cursor, from, to, 0);

    gridView.setAdapter(adapter);

I have tested returning only the text and it returns correctly, but with images I get a error:

android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string

I assume that I first have to get the image from the database?? Any help?

EDIT

I understand why you would think that this question is a duplicate of SimpleCursorAdapter how to show an image? but in that question the image is stored in the drawable folder and he is saving and calling the name of that image as a string into sqlite. In my case, the image is in the gallery and I save it as a blob into SQLite (In another activity) and now I am trying to get the blob back from the database and displaying it in a GridView.

So in the answer the following will not work for me:

int resID = getApplicationContext().getResources().getIdentifier(cursor.getString(columnIndex), "drawable",  getApplicationContext().getPackageName());
IV.setImageDrawable(getApplicationContext().getResources().getDrawable(resID));
ClassA
  • 2,480
  • 1
  • 26
  • 57

1 Answers1

0

You can use this to get blob as byte[] from SQLITE

byte[] img = cursor.getBlob(cursor.getColumnIndex(IMG_SRC));

then convert byte[] to bitmap using below Util method ...

public static Bitmap getbitmap(byte[] img) {
        return BitmapFactory.decodeByteArray(img, 0, img.length);
    }
Omar Dhanish
  • 885
  • 7
  • 18
  • Ok and how will I add each image in specific viewholder? Currently I set the text in each viewholder with SimpleCursorAdapter – ClassA Aug 02 '17 at 18:44
  • please look at my code `final int[] to` the image position is determined by the id of the row in SQLite – ClassA Aug 02 '17 at 18:59
  • ok then you retrieve the byte [] array and id from the sqlite , use if/else condition to set the imageview ,hope it helps , – Omar Dhanish Aug 02 '17 at 19:09