Asked  7 Months ago    Answers:  5   Viewed   31 times

I want to store an image(from url) into a sqlite database.

For that I use:

db = new DataBase(getApplicationContext());
URL url = new URL("");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer barb= new ByteArrayBuffer(128);

int current = 0;
while ((current = != -1) {
    barb.append((byte) current);

ContentValues filedata= new ContentValues();


db.insert(DataBase.Table_Img, null, filedata);

In the Insert():

public void insert(String tableImg, Object object,
        ContentValues dataToInsert) {
    // TODO Auto-generated method stub
    String sql = "INSERT INTO "+tableImg+" ("+ID+","+IMG_SRC+") " +
            "VALUES ('"+1+"','"+dataToInsert+"')";

For the retrieval of image:

Cursor cursor = db.selectDataToShow(DataBase.Table_Img, DataBase.IMG_SRC);

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

ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);

System.out.println(">>>>>>>>>>>>>>>>>>>>>> "+theImage);

So here I got null.

And in my database the value of image stored as: Image=[B@43e5ac48]



Here the code i used for my app

This code will take a image from url and convert is to a byte array

byte[] logoImage = getLogoImage(IMAGEURL);

private byte[] getLogoImage(String url){
     try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = != -1) {
                  baf.append((byte) current);

             return baf.toByteArray();
     } catch (Exception e) {
          Log.d("ImageManager", "Error: " + e.toString());
     return null;

To save the image to db i used this code.

 public void insertUser(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String delSql = "DELETE FROM ACCOUNTS";
        SQLiteStatement delStmt = db.compileStatement(delSql);

        String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
        SQLiteStatement insertStmt = db.compileStatement(sql);
        insertStmt.bindString(1, Integer.toString(this.accId));
        insertStmt.bindBlob(3, this.accImage);

To retrieve the image back this is code i used.

public Account getCurrentAccount() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    String sql = "SELECT * FROM ACCOUNTS";
    Cursor cursor = db.rawQuery(sql, new String[] {});

        this.accId  = cursor.getInt(0);
        this.accName = cursor.getString(1);
        this.accImage = cursor.getBlob(2);
    if (cursor != null && !cursor.isClosed()) {
    if(cursor.getCount() == 0){
        return null;
    } else {
        return this;

Finally to load this image to a imageview

logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage, 
Tuesday, June 1, 2021
answered 7 Months ago

I don't think there's a way of setting DPI with GD. The DPI of an image is specified in the leading bytes of the image data - I believe for JPEG images that's bytes 15-18. Bytes 15-16 are horizontal DPI, 17-18 vertical. The values are stored as octals.

I'm a bit ropey with byte-level editing, but you could resize the image in GD to the target pixel size and then edit the file to adjust the DPI.

Saturday, May 29, 2021
answered 7 Months ago

After many tries i solved this problem. To store image in blobstore, first android needs to make request to servlet which will generate upload url :

Android client : It will request to generate url and gets url from servlet

HttpClient httpClient = new DefaultHttpClient();    
//This will invoke "ImgUpload servlet           
HttpGet httpGet = new HttpGet("my-app-url/ImgUpload"); 
HttpResponse response = httpClient.execute(httpGet);
HttpEntity urlEntity = response.getEntity();
InputStream in = urlEntity.getContent();
String str = "";
while (true) {
    int ch =;
    if (ch == -1)
    str += (char) ch;
} - Servlet to generate url and sends response to client

BlobstoreService blobstoreService = BlobstoreServiceFactory
public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {

//"uploaded" is another servlet which will send UploadUrl and blobkey to android client
String blobUploadUrl = blobstoreService.createUploadUrl("/uploaded"); 


        PrintWriter out = resp.getWriter();

In android client,write below code upload image to returned response from above servlet.

//Save image to generated url
HttpPost httppost = new HttpPost(str);
File f = new File(imagePath);
FileBody fileBody = new FileBody(f);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileBody);
response = httpClient.execute(httppost); //Here "uploaded" servlet is automatically       invoked
urlEntity = response.getEntity(); //Response will be returned by "uploaded" servlet in JSON format
in = urlEntity.getContent();
str = "";
while (true) {
    int ch =;
    if (ch == -1)
    str += (char) ch;
JSONObject resultJson = new JSONObject(str);
String blobKey = resultJson.getString("blobKey");
String servingUrl = resultJson.getString("servingUrl"); servlet which returns Uploadurl and Blobkey of image

BlobstoreService blobstoreService = BlobstoreServiceFactory

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        try {
            List<BlobKey> blobs = blobstoreService.getUploads(req).get("file");
            BlobKey blobKey = blobs.get(0);

            ImagesService imagesService = ImagesServiceFactory
            ServingUrlOptions servingOptions = ServingUrlOptions.Builder

            String servingUrl = imagesService.getServingUrl(servingOptions);


            JSONObject json = new JSONObject();

            json.put("servingUrl", servingUrl);
            json.put("blobKey", blobKey.getKeyString());

            PrintWriter out = resp.getWriter();
        } catch (JSONException e) {


Thursday, July 29, 2021
answered 4 Months ago

You can't get a drawable id from an ImageView. But if you set it from code, you can also store it somewhere, for example in the tag field. Take a look at the similar question: Who I compare an background Image resource TextView with a R.drawable.bg_image for switch.

Saturday, October 16, 2021
answered 2 Months ago

Is this bad practice?

If it looks good at all screen densities (and sizes that you are supporting), this is perfectly fine. Only you can make that determination.

As I note in another answer, the issue is the automatic resampling, and the resulting quality.

First, screen densities keep increasing. We have -xxhdpi devices now (e.g., Droid DNA). However, -xxhdpi was a relatively recent addition to the SDK. If your icons are -xhdpi, they will be upsampled for -xxhdpi, and that could be problematic. At the moment, -xxhdpi devices are extremely few in number, though, so this may not matter for the moment. However, if you are only supplying, say, -mdpi images, Android will need to upsample for -hdpi on up, once again likely causing artifacts.

Downsampling is more likely to have decent results, compared with upsampling. However, it is not an absolute guarantee of quality, particularly as you go through several levels (e.g., downsampling -xhdpi to -ldpi).

Custom-crafting images for other densities give you absolute control over quality, at the cost of development time and APK size.

Saturday, October 23, 2021
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :