0

I'm a newbie in Android,

I just wondering how to store an image to SQLite database in Android, well i have database look like this.

Photo
id (int) | image (BLOB)

Then i have a class to get an image from gallery..

LogoSQLiDemoActivity

public class LogoSQLiteDemoActivity extends Activity implements OnClickListener{
ContactImageAdapter imageAdapter;
Validation valid;
DBDataSource db;

 private ArrayList<image> imageArry = new ArrayList<image>();
 public static final int MEDIA_TYPE_IMAGE = 1;


private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;

int imageId;
byte[] imageName;


String nama_foto;
String nama;    

Bitmap theImage;
byte imageInByte[];
private Long id;

//widget
private EditText edNama_foto;
Button addImage;
Button cancel;
ListView dataList;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_data_photo2);

    /*** create DatabaseHandler object*/
    db = new DBDataSource(this);        
    //error in here
    db.open();

    dataList        = (ListView) findViewById(R.id.list);
    cancel          = (Button)findViewById(R.id.btnCancel);
    addImage        = (Button) findViewById(R.id.btnAdd);

    cancel.setOnClickListener(this);

    Sma sekolah = db.getLastSma();
    id = sekolah.getId();



    /**
     * Reading and getting all records from database
     */ 
    List<image> img = db.getAllImage_Logo(id);
        for (image cn : img) 
        {

            // add contacts data in arrayList
            imageArry.add(cn);


            /** Set Data base Item into listview}*/
            imageAdapter = new ContactImageAdapter(this, R.layout.screen_list, imageArry);
            dataList.setAdapter(imageAdapter);

        }


    /**
     * go to next activity for detail image
    */
    dataList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                final int position, long id) {

            imageName = imageArry.get(position).getLokasi_foto();
            imageId = imageArry.get(position).get_id_sma();

            Log.d("Before Send:****", imageName + "-" + imageId);
            // convert byte to bitmap
            ByteArrayInputStream imageStream = new ByteArrayInputStream(
                    imageName);
            theImage = BitmapFactory.decodeStream(imageStream);
            Intent intent = new Intent(LogoSQLiteDemoActivity.this,
                    DisplayImageActivity2.class);
            intent.putExtra("imagename", theImage);
            intent.putExtra("imageid", imageId);
            startActivity(intent);

        }
    }); 

    /**
     * open dialog for choose camera/gallery
     */
    final String[] option = new String[] { "Ambil dari Kamera",
            "Pilih dari Album" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.select_dialog_item, option);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Pilihan");
    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            Log.e("Pilihan", String.valueOf(which));
            if (which == 0) {
                callCamera();
            }
            if (which == 1) {
                callGallery();
            }

        }
    });
    final AlertDialog dialog = builder.create();

    addImage.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.show();
        }
    });
}

/**
 * On activity result
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK)
        return;

    switch (requestCode) {
    case CAMERA_REQUEST:

        Bundle extras = data.getExtras();

        if (extras != null) {
            Bitmap yourImage = extras.getParcelable("data");
            // convert bitmap to byte
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte imageInByte[] = stream.toByteArray();
            Log.e("output before conversion", imageInByte.toString());
            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");
            db.addImage3(new image(imageInByte));
            Intent i = new Intent(LogoSQLiteDemoActivity.this, LogoSQLiteDemoActivity.class);
            startActivity(i);
            finish();
        }
        break;
    case PICK_FROM_GALLERY:
        Bundle extras2 = data.getExtras();

        if (extras2 != null) 
        {
            Bitmap yourImage = extras2.getParcelable("data");
            // convert bitmap to byte
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte imageInByte[] = stream.toByteArray();
            Log.e("output before conversion", imageInByte.toString());
            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");
            db.addImage3(new image(imageInByte));
            Intent i = new Intent(LogoSQLiteDemoActivity.this,
                    LogoSQLiteDemoActivity.class);
            startActivity(i);
            finish();
        }
    }
}

/**
 * open camera method
 */
public void callCamera() {

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra("crop", "true");
    cameraIntent.putExtra("aspectX", 0);
    cameraIntent.putExtra("aspectY", 0);
    cameraIntent.putExtra("outputX", 150);
    cameraIntent.putExtra("outputY", 150);
    cameraIntent.putExtra("return-data", true);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);


}

/**
 * open gallery method
 */

public void callGallery() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 0);
    intent.putExtra("aspectY", 0);
    intent.putExtra("outputX", 150);
    intent.putExtra("outputY", 150);
    intent.putExtra("return-data", true);
    startActivityForResult(
            Intent.createChooser(intent, "Complete action using"),
            PICK_FROM_GALLERY);
}



@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
     switch(v.getId())
        {
            case R.id.btnCancel:
                Intent intent = new Intent(getApplicationContext(), MenuAdmin.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
        }
}

}

and this a method i use to store picture in sqlite

 public void addImage3(image img) {
    open(); //it's mean to open the connection from database

            //THE Question is right here, how i can put a byte array into database 
            //without using this method, a.k.a INSERT INTO, cause i have tried to search any 
            //solution in google, but i can't solve my problem
    ContentValues values = new ContentValues();
    values.put(image, img._lokasi_foto); 

    // Inserting Row
    database.insert(Photo, null, values);
    close(); // Closing database connection
}

and here's my image class

 public class image {
 public byte[] _lokasi_foto;

 //this is getter
 public byte[] getLokasi_foto() {
return _lokasi_foto;
 }
 //this is setter
 public void setLokasi_foto(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
 }
 and this the constructor
 public image(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
  }
}

Can someone help me with this problem, cause i have been search in google, but i can't still solve my problem, Please Help...

Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40
user3747208
  • 21
  • 1
  • 6
  • Try this http://stackoverflow.com/questions/18798189/adding-image-to-android-sqlite-database or this http://stackoverflow.com/questions/8884058/sqlite-is-it-possible-to-insert-a-blob-via-insert-statement – nfirex Jun 17 '14 at 06:06
  • @nfirex: i think it same what i do in my class, it's not using insert into right? – user3747208 Jun 17 '14 at 06:11
  • Yep, your method from the first link,what problem is of your method? If you receive exception can you post it? – nfirex Jun 17 '14 at 06:23
  • @nfirex : i want to store image without the method, so i just wondering can i user INSERT INTO query to put data in sqlite? can you help me? – user3747208 Jun 17 '14 at 06:26
  • Yes, you can. If you want hardcore - look on the first part of the answer in second link: http://stackoverflow.com/a/8884362/1001401 examples of converting bytes into hexliteral: http://www.rgagnon.com/javadetails/java-0596.html Try this way, but I have not used it – nfirex Jun 17 '14 at 06:41
  • And example of insert query: http://stackoverflow.com/a/7475843/1001401 – nfirex Jun 17 '14 at 06:42

2 Answers2

0

Save the image in a local folder with the same name as your id. So now whenever you want to retrieve the image, just open id.jpg / id.png

Shivam Verma
  • 7,973
  • 3
  • 26
  • 34
0
private void saveToDB() {
        SQLiteDatabase myDb;
        String MySQL;
        byte[] byteImage1 = null;
        byte[] byteImage2 = null;
        MySQL = "create table emp1(_id INTEGER primary key autoincrement, sample TEXT not null, audio BLOB);";
        myDb = openOrCreateDatabase("Blob List", Context.MODE_PRIVATE, null);
        myDb.execSQL(MySQL);
        String s = myDb.getPath();
        textView.append("\r\n" + s + "\r\n");
        myDb.execSQL("delete from emp1");
        ContentValues newValues = new ContentValues();
        newValues.put("sample", "HI Hello");

        try {

            InputStream is = new FileInputStream("YOUR IMAGE PATH");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(b)) != -1) {
                bos.write(b, 0, bytesRead);

            }
            byte[] bytes = bos.toByteArray();

            textView.append("\r\n" + bytes.length + "\r\n");
            newValues.put("audio", bytes);

            long ret = myDb.insert("emp1", null, newValues);
            if (ret < 0)
                textView.append("\r\n!!! Error add blob failed!!!\r\n");
        } catch (IOException e) {
            textView.append("\r\n!!! Error: " + e + "!!!\r\n");
        }

        Cursor cur = myDb.query("emp1", null, null, null, null, null, null);
        cur.moveToFirst();
        while (cur.isAfterLast() == false) {
            textView.append("\r\n" + cur.getString(1) + "\r\n");
            cur.moveToNext();
        }
        // /////Read data from blob field////////////////////
        cur.moveToFirst();
        byteImage2 = cur.getBlob(cur.getColumnIndex("audio"));
        // bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
        // byteImage2.length));
        textView.append("\r\n" + byteImage2.length + "\r\n");

        cur.close();

        myDb.close();

    }
Pratik Dasa
  • 7,439
  • 4
  • 30
  • 44