package com.example.database_db_hari;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
ImageView iv;
Button b1, b2;
byte[] img1, image;
Bitmap b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.btn_activity_main_open);
b2 = (Button) findViewById(R.id.btn_activity_main_show);
iv = (ImageView) findViewById(R.id.imageView1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DataBaseHub dbh = new DataBaseHub(MainActivity.this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
// convert from bitmap to byte array
b = BitmapFactory.decodeResource(getResources(),
R.drawable.aass);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] img1 = stream.toByteArray();
cv.put(DataBaseHub.PHOTO, img1);
db.insert(DataBaseHub.TABLENAME, null, cv);
Toast.makeText(MainActivity.this, "Insert Success",
Toast.LENGTH_SHORT).show();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DataBaseHub dbh = new DataBaseHub(MainActivity.this);
SQLiteDatabase db = dbh.getReadableDatabase();
// convert from byte array to bitmap
Cursor c = db.query(DataBaseHub.TABLENAME, null, null, null,
null, null, null);
if (c.moveToFirst()) {
do {
image = c.getBlob(c.getColumnIndex("photo"));
} while (c.moveToNext());
}
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0,
image.length);
iv.setImageBitmap(bmp);
Toast.makeText(MainActivity.this, "Show Success",
Toast.LENGTH_SHORT).show();
}
});
}
}