Can't store image from SQLite to ImageView - android

i have this annoying problem.Im trying to store image from drawable folder to database then retrieve it and set it in ImageView, but when i try to store it in the ImageView and run it its not changed from the default image that i put in first place, the ImageView is gone.
Here is the code for the activity where the ImageView is and the code for the DB handler. MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.maintestImage);
images();
img.setImageBitmap(dbHandler.getImageDiet());
initNewProf();
initExercises();
}
public void images(){ //get the image from the drawable and store it in the base
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.abs)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
dbHandler.saveDiet(photo);
}` DB handler
public Bitmap getImageDiet(){ //retrive the image from the base
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT imagedata FROM "+ TABLE_DIET, null);
byte[] photo = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");
while(c.moveToNext())
{
photo=c.getBlob(3);
}
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imgView.setImageBitmap(theImage);
}

Related

Android: How to pass byte array to blob (storing camera image into sqlite)

How can I properly change this byte[] photo = getBytes(imageBitmap); to be stored in a database Blob?
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//ImageView imageview = findViewById(R.id.imageView);
//imageview.setImageBitmap(imageBitmap);
//Bitmap to bytes for database
byte[] photo = getBytes(imageBitmap);
Bitmap bmp = BitmapFactory.decodeByteArray(photo, 0, photo.length);
ImageView image = (ImageView) findViewById(R.id.imageView);
image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));
// DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());
// Walk walk = new Walk(photo);
// mydb.addWalk(walk);
}
Have you tried to use the ByteArrayOutputStream?
You can check at the documentation https://developer.android.com/reference/java/io/ByteArrayOutputStream.html
Or to make it ease you can do like this guy did
converting Java bitmap to byte array
`
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
`
First of all, what's the exact problem? Saving the image or storing it into the db?
CREATE TABLE t1 (id INTEGER PRIMARY KEY, data BLOB);
Comes down to this:
InputStream is = context.getResources().open(R.drawable.MyImageFile);
try {
byte[] buffer = new byte[CHUNK_SIZE];
int size = CHUNK_SIZE;
while(size == CHUNK_SIZE) {
size = is.read(buffer); //read chunks from file
if (size == -1) break;
ContentValues cv = new ContentValues();
cv.put(CHUNK, buffer); //CHUNK blob type field of your table
long rawId = database.insert(TABLE, null, cv); //TABLE table name
}
} catch (Exception e) {
Log.e(TAG, "Error saving raw image to: "+rawId, e);
}

How do I save the imageview created to camera roll?

In the code below, you can see that I have created an imageview using a bitmap. What I want to know is how I can save an image of that imageview to my camera roll. Thanks!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.key_code_zoom);
title = (TextView) findViewById(R.id.accountTitleLarge);
imageView = (ImageView) findViewById(R.id.keyCodeLarge);
Intent callingActivity = getIntent();
Bundle callingBundle = callingActivity.getExtras();
if (callingBundle != null) {
String titleText = callingBundle.getString("title");
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
title.setText(titleText);
imageView.setImageBitmap(bmp);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
supportFinishAfterTransition();
}
});
}
To save an image in gallery, you must first get the bitmap and then save it.
private void imageToRoll(){
imageView.buildDrawingCache();
Bitmap image = imageView.getDrawingCache(); // Gets the Bitmap
MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, imagTitle , imageDescription); // Saves the image.
}
Also, set the permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you are looking for some code that will help you save the Image from the ImageView to your phone storage then the following code will help you
public String getImageFromView() {
imageview.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
imageview.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageview.layout(0, 0, imageview.getMeasuredWidth(), imageview.getMeasuredHeight());
imageview.buildDrawingCache(true);
//Define a bitmap with the same size as the view
Bitmap b = imageview.getDrawingCache();
String imgPath = getImageFilename();
File file = new File(imgPath);
try {
OutputStream os = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 90, os);
os.flush();
os.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, "NST");
image.put(Images.Media.DISPLAY_NAME, imgPath.substring(imgPath.lastIndexOf('/')+1));
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = file.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, file.length());
image.put(Images.Media.DATA, file.getAbsolutePath());
Uri result = mContext.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgPath;
}
you will have to provide a file path getImageFilename();this function provides the path where the file is suppose to be stored. The ContentValues will be responsible to let the images be scanned in gallery.
Hope this helps.

Converting bitmap to byte and vice versa

I am currently reading an image from gallery in Bitmap format. When saving it to the database I need to convert it into byte whilst in the Image Adapter class I need to convert it to bitmap.
The following is the code: - converting to byte in order to store it in database
public void submitAction(View view)
{
/*This method creates a new post and populates it with the data added by the user. The data is then stored in the database
* using the Active Android Library.*/
Post p = new Post();
EditText title = (EditText) findViewById(R.id.post_title_input);
String tit = title.getText().toString();
EditText description = (EditText)findViewById((R.id.editText));
String desc = description.getText().toString();
Bitmap img = yourSelectedImage;
p.title=tit;
p.description=desc;
p.section="science";
int bytes = img.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
img.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
}
Code in imageAdapter class - convert the byte[] to Bitmap
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
/*Converting image to byte*/
Post p = posts.get(position);
byte[] image = p.image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(image);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(theImage);
return imageView;
}
When runnning the application, it is crashing at line Bitmap theImage = BitmapFactory.decodeStream(imageStream); and terminates with a null pointer exception.
Bitmap to byte[]
Bitmap bitmap = ...;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
byte[] to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray.length);

Converting image to string using the Base64 algorithm

I am new to android. I am trying to capture the image and store it in firebase. Since we need to convert the image to string and then store it in firebase, I am using the base64 algorithm.
The methods for capturing image and storing it in the database is :
public void capturePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(photo);
}
}
public void storeDatabase(View v)
{
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRollno.getText().toString());
ref1.child("Marks").setValue(editmarks.getText().toString());
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
n++;
}
When I click on the submit button, it takes a lot of time to upload the values. Moreover, many a times I can see the line
Skipped 537 frames! The application may be doing too much work on its main thread.
in the Android Monitor.
If I comment the image processing lines, it is working all fine.
Can somebody please tell me how to avoid such error so that the image is uploaded instantly in my database.
For storing it to the database, I would definitely use AsyncTask for this one. So, what you could have is a separate class that does the following:
private class ImageDBManager extends AsyncTask< String, Integer, Void> {
protected Long doInBackground(String... items) {
int count = items.length;
String editRoll = items[0];
String editName = items[1];
String editMarks = items[2];
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRoll);
ref1.child("Marks").setValue(editName);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(){
}
}
And then call it like this:
public void storeDatabase(View v) {
ImageDBManager manager = new ImageDBManager();
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
manager.execute(new String[] { editRollno.getText(), editname.getText(), editmarks.getText() }
}
If you are capturing the image from the camera, the best reference is here
http://developer.android.com/training/camera/photobasics.html
it's the same idea of starting an activity and implementing onActivityForResult where you get the data from the extras in the result, so instead of getting the bitmap from the R.drawable.abc, you'd get it like this in onActivityForResult
Bitmap imageBitmap = (Bitmap) extras.get("data");

URL image to imageview to drawable

ImageView img1;
img1 = (ImageView) findViewById (R.id.img1);
URL newurl = new URL("http://10.0.2.2:80/Gallardo/Practice/files/images/donut.jpg");
Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
img1.setImageBitmap(mIcon_val);
I get image from url but I want to store it to my drawable, how?
Everything in the apk will be read only.
So you can't write to drawable.
you have to use "blob" to store image.
ex: to store a image in to db
public void insertImg(int id , Bitmap img ) {
byte[] data = getBitmapAsByteArray(img); // this is a function
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
to retrieve a image from db
public Bitmap getImage(int i){
String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);
if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}
return null ;
}
You can also check this saving image to database
You can construct Drawable by using this constructor:
Drawable drawable = new BitmapDrawable(getResources(), mIcon_val);
You can set it to the ImageView like so:
img1.setImageDrawable(drawable);
Its not possible to place image in drawable folder while running the apk.. Saving an image to SDcard is possible..

Categories

Resources