2

I'm getting a problem in inserting an image from url to sqlite database.

public class MainActivity extends Activity {
      protected SQLiteDatabase sqlitedatabase_obj;
      DataBaseHelper databasehlpr_obj;
      int accId;
      byte[] accImage;

      byte[] logoImage;
      byte[] photo;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          AndroidContext.setContext(this);
          sqlitedatabase_obj = DataBaseHelper.getInstance().getDb();
          sqlitedatabase_obj.delete(DataBaseHelper.IMG_table, null, null);
          logoImage = getLogoImage("http://images.bestbuy.com/images/small_137385013870957.jpg");
          insertUser();


      }

      private byte[] getLogoImage(String url) {
           try {
               URL imageUrl = new URL(url);
               URLConnection ucon = imageUrl.openConnection();
               System.out.println("11111");
               InputStream is = ucon.getInputStream();
               System.out.println("12121");

               BufferedInputStream bis = new BufferedInputStream(is);
               System.out.println("22222");

               ByteArrayBuffer baf = new ByteArrayBuffer(500);
               int current = 0;
               System.out.println("23333");

               while ((current = bis.read()) != -1) {
                    baf.append((byte) current);

               }
               photo = baf.toByteArray();
               System.out.println("photo length" + photo);


          } catch (Exception e) {
           Log.d("ImageManager", "Error: " + e.toString());
          }
          return accImage;
     }
     public void insertUser() {
           ContentValues userdetailValues = new ContentValues();
           userdetailValues.put("account_image", photo);
           sqlitedatabase_obj.insert(DataBaseHelper.IMG_table, null, userdetailValues);
    }
}

I am creating a database as below-

final String[] creatStatments = new String[]{"create table "
            + IMG_table
            + "(account_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"+" account_image BLOB NOT NULL)",

All the above code to save image from url in sqlite database. But i am getting a Exception as below

Error: java.net.UnknownHostException: images.100bestbuy.com
Error inserting account_image=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
    at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
    at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
    at com.example.urltodatabase.MainActivity.insertUser(MainActivity.java:75)
    at com.example.urltodatabase.MainActivity.onCreate(MainActivity.java:39)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    at dalvik.system.NativeStart.main(Native Method)

When i go through to find where is problem then i found that problem is in

InputStream is = ucon.getInputStream();

So, please some one get me out of this problem. I will really very glad for my porblem resolving effort.Thanks in advance to all

MuTiny
  • 261
  • 1
  • 7
  • 23
DJhon
  • 1,548
  • 3
  • 22
  • 39
  • use asyncTask for download the image – Sunil Kumar Jul 05 '13 at 06:40
  • First: I see Error: java.net.UnknownHostException: images.100bestbuy.com . Itseems your url has some issue, try to access the same in browser and check. Second: for better performance use AsyncTask. – vinay kumar Jul 05 '13 at 06:52
  • Thanks for your response. MY correct url is http://images.100bestbuy.com/images/small_137385013870957.jpg – DJhon Jul 05 '13 at 06:56
  • How i will use AsyncTAsk. will you please post some for which have concern with my code. I will be really very thank full for that – DJhon Jul 05 '13 at 06:59

1 Answers1

3

It is not recommended to store your entire image as a blob in your sqlite database. Instead download it to a certain location in sd and save that path in a column in your sqlite db. Also, there is a bug in the android Cursor class that will not handle correctly the images that are bigger in size than 1MB. See here. To download image from an AsyncTask you can use something like this:

public class MainActivity extends Activity {
    protected SQLiteDatabase sqlitedatabase_obj;
    DataBaseHelper databasehlpr_obj;
    int accId;
    byte[] accImage;

    byte[] logoImage;
    byte[] photo;@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AndroidContext.setContext(this);
    sqlitedatabase_obj = DataBaseHelper.getInstance().getDb();
    new ImageDownloader().execute("http://images.100bestbuy.com/images/small_137385013870957.jpg");


}

private byte[] getLogoImage(String url) {
    try {
    URL imageUrl = new URL(url);
    URLConnection ucon = imageUrl.openConnection();
    System.out.println("11111");
    InputStream is = ucon.getInputStream();
    System.out.println("12121");

    BufferedInputStream bis = new BufferedInputStream(is);
    System.out.println("22222");

    ByteArrayBuffer baf = new ByteArrayBuffer(500);
    int current = 0;
    System.out.println("23333");

    while ((current = bis.read()) != -1) {
        baf.append((byte) current);

    }
    photo = baf.toByteArray();
    System.out.println("photo length" + photo);


} catch (Exception e) {
    Log.d("ImageManager", "Error: " + e.toString());
}
return accImage;
}
public void insertUser() {
    ContentValues userdetailValues = new ContentValues();
    userdetailValues.put("account_image", photo);
    sqlitedatabase_obj.insert(DataBaseHelper.IMG_table, null, userdetailValues);
}

private class ImageDownloader extends AsyncTask<String, Void, Void> {

    private ProgressDialog progressDialog;

    @Override
    protected Void doInBackground(String... param) {

         sqlitedatabase_obj.delete(DataBaseHelper.IMG_table, null, null);
         logoImage = getLogoImage(param[0]);

         insertUser();
    }

    @Override
    protected void onPreExecute() {

        progressDialog = ProgressDialog.show(MainActivity.this,
                "Wait", "Downloading Image");

    }

    @Override
    protected void onPostExecute(Void result) {
        progressDialog.dismiss();

    }

}

}
Community
  • 1
  • 1
AggelosK
  • 4,313
  • 2
  • 32
  • 37