title: Error when trying to retrieve BLOB image from database
body: <p>I didn't receive any responses back on my first question that was similar to this one, so i'm going to try this again but to hopefully explain it better so you all understand. </p>
  
  <p>I am trying to retrieve an image from the database that is stored as BLOB image  that is pulled through SIMPLECURSORADAPTER. I can store the image fine, but when I try and retrieve the image it gives me an error "Unable to convert blob to string". I'm not exactly sure why I would get this error as I'm not trying to convert the blob directly to string. </p>
  
  <p>I'm fairly new a android programming so I will take as much help as I can get.</p>
  
  <p>Thank you for your time.  </p>
  
  <blockquote>
    <p>StackTrace</p>
  </blockquote>
  
  <pre><code>  04-06 14:34:00.163    4145-4145/com.gnumbu.errolgreen.importedapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
  Process: com.gnumbu.errolgreen.importedapplication, PID: 4145
  android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string
          at android.database.CursorWindow.nativeGetString(Native Method)
          at android.database.CursorWindow.getString(CursorWindow.java:438)
          at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
          at android.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:150)
          at android.widget.CursorAdapter.getView(CursorAdapter.java:254)
          at android.widget.AbsListView.obtainView(AbsListView.java:2344)
          at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
          at android.widget.ListView.onMeasure(ListView.java:1182)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
          at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
          at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
          at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
          at android.view.View.measure(View.java:17430)
          at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1456)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
          at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
          at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
          at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
          at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
          at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
          at android.view.View.measure(View.java:17430)
          at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
          at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
          at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
          at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
          at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
          at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
          at android.view.Choreographer.doCallbacks(Choreographer.java:580)
          at android.view.Choreographer.doFrame(Choreographer.java:550)
          at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
          at android.os.Handler.handleCallback(Handler.java:739)
          at android.os.Handler.dispatchMessage(Handler.java:95)
          at android.os.Looper.loop(Looper.java:135)
          at android.app.ActivityThread.main(ActivityThread.java:5221)
          at java.lang.reflect.Method.invoke(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:372)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
  </code></pre>
  
  <blockquote>
    <p>DBAdapter.java</p>
  </blockquote>
  
  <p>public class DBAdapter {</p>
  
  <pre><code>private static final String TAG = "DBAdapter"; //used for logging database version changes
  
  // Field Names:
  public static final String KEY_ROWID = "_id";
  public static final String KEY_TASK = "task";
  public static final String KEY_DATE = "date";
  public static final String KEY_IMAGE = "image";
  
  public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TASK, KEY_DATE, KEY_IMAGE};
  
  // Column Numbers for each Field Name:
  public static final int COL_ROWID = 0;
  public static final int COL_TASK = 1;
  public static final int COL_DATE = 2;
  public static final int COL_IMAGE = 3;
  
  // DataBase info:
  public static final String DATABASE_NAME = "dbToDo";
  public static final String DATABASE_TABLE = "mainToDo";
  public static final int DATABASE_VERSION = 1; // The version number must be incremented each time a change to DB structure occurs.
  
  //SQL statement to create database
  private static final String DATABASE_CREATE_SQL = 
          "CREATE TABLE " + DATABASE_TABLE 
          + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
          + KEY_TASK + " TEXT NOT NULL, "
          + KEY_DATE + " TEXT"
          + KEY_IMAGE + " BLOB"
          + ");";
  
  
  private final Context context;
  private DatabaseHelper myDBHelper;
  private SQLiteDatabase db;
  
  
  public DBAdapter(Context ctx) {
      this.context = ctx;
      myDBHelper = new DatabaseHelper(context);
  }
  
  // Open the database connection.
  public DBAdapter open() {
      db = myDBHelper.getWritableDatabase();
      return this;
  }
  
  // Close the database connection.
  public void close() {
      myDBHelper.close();
  }
  
  // Add a new set of values to be inserted into the database.
  public long insertRow(String task, String date, byte[] image ) {
      ContentValues initialValues = new ContentValues();
      initialValues.put(KEY_TASK, task);
      initialValues.put(KEY_DATE, date);
      initialValues.put(KEY_IMAGE, image);
  
  
      // Insert the data into the database.
      return db.insert(DATABASE_TABLE, null, initialValues);
  }
  
  // Delete a row from the database, by rowId (primary key)
  public boolean deleteRow(long rowId) {
      String where = KEY_ROWID + "=" + rowId;
      return db.delete(DATABASE_TABLE, where, null) != 0;
  }
  
  public void deleteAll() {
      Cursor c = getAllRows();
      long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
      if (c.moveToFirst()) {
          do {
              deleteRow(c.getLong((int) rowId));              
          } while (c.moveToNext());
      }
      c.close();
  }
  
  // Return all data in the database.
  public Cursor getAllRows() {
      String where = null;
      Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
      if (c != null) {
          c.moveToFirst();
      }
      return c;
  }
  
  // Get a specific row (by rowId)
  public Cursor getRow(long rowId) {
      String where = KEY_ROWID + "=" + rowId;
      Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                      where, null, null, null, null, null);
      if (c != null) {
          c.moveToFirst();
      }
      return c;
  }
  
  // Change an existing row to be equal to new data.
  public boolean updateRow(long rowId, String task, String date, byte[] image) {
      String where = KEY_ROWID + "=" + rowId;
      ContentValues newValues = new ContentValues();
      newValues.put(KEY_TASK, task);
      newValues.put(KEY_DATE, date);
      newValues.put(KEY_IMAGE, image);
      // Insert it into the database.
      return db.update(DATABASE_TABLE, newValues, where, null) != 0;
  }
  
  
  private static class DatabaseHelper extends SQLiteOpenHelper
  {
      DatabaseHelper(Context context) {
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
  
      @Override
      public void onCreate(SQLiteDatabase _db) {
          _db.execSQL(DATABASE_CREATE_SQL);           
      }
  
      @Override
      public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
          Log.w(TAG, "Upgrading application's database from version " + oldVersion
                  + " to " + newVersion + ", which will destroy all old data!");
  
          // Destroy old database:
          _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
  
          // Recreate new database:
          onCreate(_db);
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <blockquote>
    <p>PeekFragment.java</p>
  </blockquote>
  
  <pre><code>public class PeekFragment extends Fragment implements View.OnClickListener {
  
  
      //Delcare Public Variables !
      Time today = new Time(Time.getCurrentTimezone());
      DBAdapter myDB;
      EditText etTasks;
      ImageView img;
      ByteArrayBuffer baf ;
      ImageView dbimage ;
  
  
  
  
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
          View v = inflater.inflate(R.layout.other_layout, container, false);
          Button a = (Button) v.findViewById(R.id.addTask);
          Button b = (Button) v.findViewById(R.id.deleteButton);
          a.setOnClickListener(this);
          b.setOnClickListener(this);
  
          return v;
      }
  
      @Override
      public void onClick(View v) {
          switch (v.getId()) {
              case R.id.addTask:
  
                  today.setToNow();
                  String timestamp = today.format("%Y-%-m-%d %H:%M:%S");
  
                  if (!TextUtils.isEmpty(etTasks.getText().toString())) {
  
                      dbimage.buildDrawingCache();//Draws image to bitmap
                      Bitmap bmap = dbimage.getDrawingCache();
  
                      myDB.insertRow(etTasks.getText().toString(), timestamp, getBytes(bmap));
  
                  }
                  break;
              case R.id.deleteButton:
                  myDB.deleteAll();
                  break;
          }
          populateListView();
      }
  
  
  
      public void onActivityCreated(Bundle savedInstanceState) {
          super.onActivityCreated(savedInstanceState);
          etTasks = (EditText) getView().findViewById(R.id.editTextTask);
          dbimage = (ImageView) getView().findViewById(R.id.dbImageUpload);
          openDB();
         // new Task_like_flag().execute();
         // img =(ImageView) getView().findViewById(R.id.imageViewpicture);
          populateListView();
          listViewItemClick();
          listViewItemLongClick();
  
          Cursor cursor = myDB.getAllRows();
  
          String[] fromFieldNames = new String[]{DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK, DBAdapter.KEY_IMAGE};
          int[] toViewIDs = new int[]{R.id.idView, R.id.resourceView, R.id.imageViewpicture};
          SimpleCursorAdapter myCursorAdapter;
          myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.tobedeletedd_view, cursor, fromFieldNames, toViewIDs, 0) {
          };
          ListView myList = (ListView) getView().findViewById(R.id.listView);
  
          myList.setAdapter(myCursorAdapter);
  
      }
  
      /**
       * public void onClick_AddTask(View v) {
       * today.setToNow();
       * String timestamp = today.format("%Y-%-m-%d %H:%M:%S");
       * &lt;p/&gt;
       * if (!TextUtils.isEmpty(etTasks.getText().toString())) {
       * myDB.insertRow(etTasks.getText().toString(), timestamp);
       * &lt;p/&gt;
       * }
       * populateListView();
       * }
       */
  
      private void openDB() {
          myDB = new DBAdapter(getActivity());
          myDB.open();
      }
  
      private void populateListView() {
          Cursor cursor = myDB.getAllRows();
  
          String[] fromFieldNames = new String[]{DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK, DBAdapter.KEY_IMAGE};
          int[] toViewIDs = new int[]{R.id.idView, R.id.resourceView, R.id.imageViewpicture};
          SimpleCursorAdapter myCursorAdapter;
          myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.tobedeletedd_view, cursor, fromFieldNames, toViewIDs, 0) {
          };
          ListView myList = (ListView) getView().findViewById(R.id.listView);
  
          myList.setAdapter(myCursorAdapter);
  
      }
  
      private void updateTask(long id) {
          Cursor cursor = myDB.getRow(id);
  
          if (cursor.moveToFirst()) {
              String task = etTasks.getText().toString();
              today.setToNow();
              String date = today.format("%Y-%-m-%d %H:%M:%S");
  
              dbimage.buildDrawingCache();//Draws image to bitmap
              Bitmap bmap = dbimage.getDrawingCache();
  
              myDB.updateRow(id, task, date,getBytes(bmap));
          }
  
          cursor.close();
      }
  
      private void listViewItemClick() {
          ListView myList = (ListView) getView().findViewById(R.id.listView);
          myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
                  updateTask(id);
                  populateListView();
              }
          });
      }
  
  
  
  
      private void listViewItemLongClick() {
          ListView myList = (ListView) getView().findViewById(R.id.listView);
  
          myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  
  
              @Override
              public boolean onItemLongClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
                  myDB.deleteRow(id);
                  populateListView();
  
                  return false;
              }
          });
  
      }
  /**
      public Bitmap convertBlobToBitmap(byte[] blobByteArray) {
          Bitmap tempBitmap=null;
          if(blobByteArray!=null)
              tempBitmap = BitmapFactory.decodeByteArray(blobByteArray, 0, blobByteArray.length);
          return tempBitmap;
      }
      public class Task_like_flag extends AsyncTask&lt;String, Void, Void&gt; {
          private final ProgressDialog dialog = new ProgressDialog(getActivity());
          JSONObject object_feed;
          // can use UI thread here
          protected void onPreExecute() {
              this.dialog.setMessage("Loading...");
              this.dialog.setCancelable(false);
              this.dialog.show();
          }
  
          @Override
          protected Void doInBackground(String... params) {
              URL url = null;
              try {
                  url = new URL("http://i.imgur.com/cWdWl6L.png");
              } catch (MalformedURLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }  //http://example.com/image.jpg
              //open the connection
              URLConnection ucon = null;
              try {
                  ucon = url.openConnection();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              //buffer the download
              InputStream is = null;
              try {
                  is = ucon.getInputStream();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              BufferedInputStream bis = new BufferedInputStream(is,128);
              baf = new ByteArrayBuffer(128);
              //get the bytes one by one
              int current = 0;
              try {
                  while ((current = bis.read()) != -1) {
                      baf.append((byte) current);
                  }
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              today.setToNow();
              String timestamp = today.format("%Y-%-m-%d %H:%M:%S");
              String voteText = "Test";
              myDB.insertRow(etTasks.getText().toString(), timestamp, baf.toByteArray(), voteText);
              return null;
          }
  
          @Override
          protected void onPostExecute(Void result) {
              byte[] imageByteArray;
              Bitmap theImage = null;
              try{
                  Cursor cursor = myDB.fetchAllNotes();
                 // startManagingCursor(myDB);
  
                  if (cursor.moveToFirst()) {
  
  
                      do {
                          imageByteArray   =  cursor.getBlob(cursor.getColumnIndex(DBAdapter.KEY_IMAGE));
                          ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
                          theImage= BitmapFactory.decodeStream(imageStream);
  
                      } while (cursor.moveToNext());
                  }
              }catch(Exception e){
                  Log.v("Excep", ""+e);
              }
              img.setImageBitmap(theImage);
              if (this.dialog.isShowing()) {
                  this.dialog.dismiss();
              }
          }
      }
  */
  
  
      // convert from bitmap to byte array
      public static byte[] getBytes(Bitmap bitmap) {
          ByteArrayOutputStream stream = new ByteArrayOutputStream();
          bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
          return stream.toByteArray();
      }
  
      // convert from byte array to bitmap
      public static Bitmap getImage(byte[] image) {
          return BitmapFactory.decodeByteArray(image, 0, image.length);
      }
  
  }
  </code></pre>