I created a simple app in which the image store from the ImageView to the database.
But when click on the retrive button is show that index 1 requested with size of 3.
I don't know what thing is going wrong.
database class:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_IMAGE_TABLE = "CREATE TABLE " +TABLE_NAME + "("
+ IMAGE_KEY + " BLOB )";
db.execSQL(CREATE_IMAGE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(byte[]image )throws SQLiteException
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(IMAGE_KEY,image);
long result= db.insert(TABLE_NAME,null,cv);
if(result==-1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
byte[]img=res.getBlob(0);
return res;
}
And this is the activity class:
public void button2(View view)
{
try {
Cursor res = myDb.getAllData();
if (res ==null) {
showMessage("error", "no data found");
} else {
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("id:" + res.getBlob(0) + "\n");
byte[] image = res.getBlob(0);
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0,
image.length);
imagee.setImageBitmap(bmp);
}
// showMessage("DATA", buffer.toString());
}
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),
Toast.LENGTH_LONG).show();
}}
public void buttonn(View view)
{
Bitmap bitmap = ((BitmapDrawable) imagee.getDrawable()).getBitmap();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();
boolean isInserted = myDb.insertData(data);
if (isInserted == true)
Toast.makeText(getBaseContext(), "Registration Succes!",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(getBaseContext(), "No Record Registered!",
Toast.LENGTH_SHORT).show();
}
}
I tried most but couldn't do not thing.I change it from res.movetoNext but show the same error and use res.movetoFirst it also show the same error
Android sqlite CursorWindow has a fixed size buffer that is 2MB on most configurations. You cannot move around rows any larger than that.
Don't store large binary data such as images in Android sqlite. Use external storage instead and just save the path in your database.
Check this code about how to save an image in android:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
return directory.getAbsolutePath();
}
You need just to add the path of your image into your database instead of the blob image.
Reference: Saving and Reading Bitmaps/Images from Internal memory in Android
Related
I am trying to write an image on storage then reading it. Write operation is successful but read fails. I have tried using intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); when calling the responsible activity but was of no help.
This is how I write image:
public void savepic(Bitmap pic)
{
SQLiteDatabase db = dBcontract.getWritableDatabase();
ContentValues values = new ContentValues();
FileOutputStream out = null;
try
{
File image = createImageFile();
Uri photoURI = FileProvider.getUriForFile(context, "lcukerd.com.android.fileprovider", image);
out = new FileOutputStream(image);
pic.compress(Bitmap.CompressFormat.PNG, 100, out);
values.put(eventDBcontract.ListofItem.columnpic, photoURI.toString());
db.insert(eventDBcontract.ListofItem.tableName2, null, values);
Log.i(TAG, "Pic saved " + photoURI.toString());
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (out != null)
{
out.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
private File createImageFile() throws IOException
{
String EName = "Image";
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(EName, ".jpg", storageDir);
return image;
}
This is how I read image:
public Bitmap getDownloadedpics(int index)
{
SQLiteDatabase db = dBcontract.getReadableDatabase();
Cursor cursor = db.query(eventDBcontract.ListofItem.tableName2, projection2, null, null, null, null, null);
cursor.moveToPosition(index);
Bitmap photo = null;
try
{
Log.d(TAG,cursor.getString(cursor.getColumnIndex(eventDBcontract.ListofItem.columnpic)));
photo = MediaStore.Images.Media.getBitmap(context.getContentResolver(),
Uri.parse(cursor.getString(cursor.getColumnIndex(eventDBcontract.ListofItem.columnpic))));
} catch (IOException e)
{
Log.e(TAG, "Can't read image");
}
Log.d(TAG, "Returned " + String.valueOf(cursor.getCount()) + " pics");
return (photo);
}
I get Exception at `photo =
MediaStore.Images.Media.getBitmap(context.getContentResolver(),
Uri.parse(cursor.getString(cursor.getColumnIndex(eventDBcontract.ListofItem.columnpic))));
Exception is :
java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{6118b35 21772:lcukerd.com.instaswipe/u0a157} (pid=21772, uid=10157) that is not exported from uid 10101
I have checked other similar question but seems like they are all for some other type of problem. Help me solve it.
Instead of photoUri.toString() put image.getAbsolutePath() in your database.
If you want to read the file get the path from the database. Construct a File object en use FileInputStream. Then let BitmapFactory read the data from the stream.
I am storing an image taken from camera into sqlite database can anybody help me to retrieve the same image and i want to show that image in a image view.
Here is my Database handler class method for saving the image
public long insert(Bitmap img ) {
SQLiteDatabase base=this.getWritableDatabase();
byte[] data = getBitmapAsByteArray(img); // this is a function
ContentValues value=new ContentValues();
value.put("image",data);
long a= base.insert("Mypic", null, value);
System.out.println("check1" + a);
return a;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
Please help me for writing the method how i can get the image and display the image in an imageview.
To insert Image on database:
Bitmap bitmap = ((BitmapDrawable) image_imgv.getDrawable()).getBitmap();
ByteArrayOutputStream bos4 = new ByteArrayOutputStream();
bitmap4.compress(Bitmap.CompressFormat.PNG, 100, bos4);
image = bos4.toByteArray();
database = new BBDD(this, "BBDD", null, 1);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues reg = new ContentValues();
reg.put("img", image);
To retrieve:
database2 = new BBDD(Activity.this, "BBDD", null, 1);
SQLiteDatabase db2 = database2.getReadableDatabase();
if (db2 != null)
{
Cursor cursor = db2.rawQuery("SELECT img FROM database2, null);
if (cursor.moveToFirst())
{
img=cursor.getBlob(cursor.getColumnIndex("img"));
Bitmap b1=BitmapFactory.decodeByteArray(image, 0, image.length);
image_imageview.setImageBitmap(b1);
}
else
Toast.makeText(Activity.this, "Error.", Toast.LENGTH_LONG).show();
db2.close();
}
else
Toast.makeText(sActivity.this, "Error db.", Toast.LENGTH_LONG).show();
}
});
I'm currently creating thumbnails by using the ThumbnailUtils.createVideoThumbnail() method; which returns a bitmap. However, I want to store that thumbnail in a database so I can access it later and I don't have to keep recreating the thumbnails. My questions is how should I store this thumbnail in the database? Do thumbnails have filepaths? Or should I create the thumbnails and just retrieve them using the Mediastore every time I need to use it? If so how would I go about saving/storing the thumbnail so I can use the Mediastore to query it?
Thanks for your help.
If you're getting a Thumbnail object from video, you need to save it in either storage or database.
To save in database :
Bitmap thumbnailBitmap; // Get it with your approach
SQLiteDatabase writableDb; // Get it with your approach
if (thumbnailBitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnailBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] thumbnailBitmapBytes = stream.toByteArray();
ContentValues values = new ContentValues();
values.put("IMAGEID", "your_image_id");
values.put("BYTES", thumbnailBitmapBytes);
writableDb.insert("TABLE_NAME", null, values);
}
To get it back from database :
public static synchronized Bitmap getImage(String imageID, Context context) {
SQLiteDatabase writableDb; // Get it with your approach
Bitmap bitmap = null;
Cursor cs = null;
try {
String sql = "SELECT BYTES FROM TABLE_NAME WHERE IMAGEID = ?;";
cs = writableDb.rawQuery(sql, new String[]{imageID});
if (cs != null && cs.moveToFirst()) {
do {
byte[] bytes = cs.getBlob(0);
if (bytes != null) {
try {
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
} catch (Exception e) {
Log.e("TAG", "Exception", e);
}
} else {
Log.e("TAG", "IMAGE NOT FOUND");
}
} while (cs.moveToNext());
}
} catch (Exception e) {
Log.e("TAG", "Exception", e);
} finally {
if (cs != null) {
cs.close();
}
}
return bitmap;
}
The database structure:
String imageTable = "CREATE TABLE TABLE_NAME("
+ "IMAGEID TEXT PRIMARY KEY, "
+ "BYTES BLOB)";
Hey i am new in android application development.i currently develop
application, in some phase of that application deal with the image
store , retrieve and delete
how can i store whole image in android ? and how can i retrieve more
than one images which i uploaded in SQLite wants in gallery view?
please give me some guidance or link of blogs which deal with such
image processing in android
If u are dealing with images copy the image to separate folder and store the path in database OR store the image bytearray in db if size of image is small.
try this
public class ImageConvertScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button img_byte,byte_img;
ImageView image;
TextView value;
public ByteArrayOutputStream bos;
public Bitmap bm;
public byte[] bitmapdata;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextr);
image = (ImageView) findViewById(R.id.img_convert);
value=(TextView)findViewById(R.id.convert_txt);
img_byte =(Button)findViewById(R.id.img_byte);
byte_img =(Button)findViewById(R.id.byte_img);
img_byte.setOnClickListener(this);
byte_img.setOnClickListener(this);
String imgName = "ic_launcher";
String KEY_IMG = "/mnt/sdcard/DCIM/Camera/IMG_20121021_150153.jpg";
File f = new File(Environment.getExternalStorageDirectory(), KEY_IMG);
String path =Environment.getExternalStorageDirectory().getPath()+"/image4.png";
//bm = BitmapFactory.decodeFile(path);
bm = BitmapFactory.decodeResource(getResources(),getResId(imgName, R.drawable.class));
bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 20 , bos);
}
public void onClick(View v) {
if (v == img_byte) {
bitmapdata = bos.toByteArray();
Log.w("Image Conversion", String.valueOf(bitmapdata.length));
String converted_txt="";
Toast.makeText(getBaseContext(), ""+bitmapdata.length,1).show();
for (int i = 0; i < bitmapdata.length; i++) {
Log.w("Image Conversion", String.valueOf(bitmapdata[i]));
converted_txt=converted_txt+bitmapdata[i];
}
saveImageOnSDCard1("testingImg",bitmapdata);
value.setText(converted_txt);
value.setVisibility(View.VISIBLE);
image.setVisibility(View.INVISIBLE);
} else if (v==byte_img){
bm = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
image.setImageBitmap(bm);
image.setVisibility(View.VISIBLE);
value.setText("");
value.setVisibility(View.INVISIBLE);
Log.w("Image Conversion", "converted");
}
}
public int getResId(String variableName, Class<?> c) {
Field field = null;
int resId = 0;
try {
field = c.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
public static void saveImageOnSDCard1(String imageName, byte[] data) {
File file1 = new File(Environment.getExternalStorageDirectory()
+ "/isus/");
if (!file1.exists()) {
boolean isCreated = file1.mkdirs();
Log.e("Directory Created", "Directory Created " + isCreated);
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/isus/" + imageName + ".png");
Log.i("path",""+file.getAbsolutePath().toString());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data);
} catch (Exception e) {
Log.i("err",""+e.getLocalizedMessage());
} finally {
try {
fileOutputStream.close();
} catch (Exception e2) {
}
}
}
}
my question is that i have a code that is suppose to receive a variable that contains a website that has an image so this variable changes every time i send a new link this code should go online and download the image and save it to the sd-card then i read it and display it
so my problem with the code is if im sending 2 links to it, it downloads 1 of the images and it always stores it with the second image name (example: im sending image1 and image2 the code downloads image1 two times and stores it as "image2") when i mount the sd-card and check the image directory there is only 1 image there named image2, i thought that doInBackground was causing the problem but im also using onPostExecute() so please if someone can help me i would be thankful for his help Note this is how i call it:
Note: i have no errors in the code // no red marks
This is all the code:
private void UpdateAds(String Bookinfo,TextView myText){
elhgsdatabase db = new elhgsdatabase(this);
if (Bookinfo != "didn't read titels"){
String debContent="";
String output ="";
int NUMBEROFFIELDS = 5;
String s = addressString;
long idx;
String [] buffer = new String[NUMBEROFFIELDS];
output = "";
int l = 0;
while (s.indexOf("[")>-1){
int fk = s.indexOf("[");
int fl = s.indexOf("]");
if(fk > -1){
buffer[l] = s.substring(fk+1, fl);
s = s.substring(fl+1);
l++;
if (l == NUMBEROFFIELDS){
//1. Query the database to check if the book exists
//---get all titles---
db.open();
Cursor c = db.getBookTitle (buffer[0]);
if (c.getCount()==1)
{ myText.setText("This Books Exist \n"); }
else if(c.getCount()==0)
{ String locLink;
locLink = getLocalLink(buffer[3], buffer[0]);
c.moveToFirst();
if (!locLink.equalsIgnoreCase("-1")){
idx= db.insertTitle(buffer[0], buffer[1], buffer[2], getDate(buffer[3]), buffer[4], locLink);
}
else { //there was a problem with retrieval-saving of the Book info locally
myText.setText("There was a problem with retrieval-saving of the Book info locally\n");
}
}//if(c.getCount()==0)
else{//The table has two Books with the same Name. Do something
myText.setText("The table has two Books with the same Name\n");
}
c.close();
l = 0;
}//if(l == NUMBEROFFIELDS)
} //if (fk>-1)
}//while
db.close();
} //of if(BookInfo...
else {
myText.setText("Nothing is Done\n");
}
}
//This method gets the local link field of the active book records
// it goes on the web, gets the content and stores it in a place
// and saves the path of that place in the database for that
//it returns -1 if something wrong happened during the process
public String getLocalLink(String image_URL, String BookName){
/** This is what we do with this method:
* Go online, according to the link, get the content, call the method to save, get the local link
* and return it
*/
setContentView(R.layout.main);
reviewImageLink = image_URL;
URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
try {
reviewImageURL = new URL(reviewImageLink);
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
new DownloadImageTask().execute(reviewImageURL);
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
.getString(R.string.directory));
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");
}
} catch (MalformedURLException e) {
Log.v(TAG, e.toString());
}
return ("/sdcard/Hanud/"+BookName+".jpg");
}
private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
// This class definition states that DownloadImageTask will take String
// parameters, publish Integer progress updates, and return a Bitmap
protected Bitmap doInBackground(URL... paths) {
URL url;
try {
url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);}
else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length- downloaded);
}
else {read = is.read(imageData, downloaded, buffersize);}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
if (result != null) {
hasExternalStoragePublicPicture(name);
saveToSDCard(result, name);
isImage = true;
} else {
isImage = false;
}
}
}
public void saveToSDCard(Bitmap bitmap, String name) {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
Log.v(TAG, "SD Card is available for read and write "
+ mExternalStorageAvailable + mExternalStorageWriteable);
saveFile(bitmap, name);
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
Log.v(TAG, "SD Card is available for read "
+ mExternalStorageAvailable);
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
Log.v(TAG, "Please insert a SD Card to save your Video "
+ mExternalStorageAvailable + mExternalStorageWriteable);
}
}
private void saveFile(Bitmap bitmap, String name) {
String filename = name;
ContentValues values = new ContentValues();
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
sdImageMainDirectory.mkdirs();
File outputFile = new File(sdImageMainDirectory, filename);
values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
values.put(MediaStore.MediaColumns.TITLE, filename);
values.put(MediaStore.MediaColumns.DATE_ADDED, System
.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
Uri uri = this.getContentResolver().insert(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
try {
OutputStream outStream = this.getContentResolver()
.openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean hasExternalStoragePublicPicture(String name) {
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
File file = new File(sdImageMainDirectory, name);
if (file != null) {
file.delete();
}
return file.exists();
}
public void showAllBooks( )
{
final elhgsdatabase db = new elhgsdatabase(this);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Get new entry
db.open();
long currTime = System.currentTimeMillis();
String p_query = "select * from ads where timeFrom<=?";
Cursor c = db.rawQuery(p_query, new String[] { Long.toString(currTime)});
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
}, 5000); // 5000 miliseconds
}
public long getDate(String s){
String[] formats = new String[] {
"yyyy-MM-dd HH:mm:ss"
};
SimpleDateFormat sdf=null;
String st;
for (String format : formats) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("EST"));//UTC or EST
st = new String(sdf.format(new Date(0)));
System.err.format(format, st);
}
Calendar c = Calendar.getInstance();
Date dt;
try {
dt = sdf.parse(s);
c.setTime(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c.getTimeInMillis() ;
}
public void DisplayTitle(final Cursor c)
{
Toast.makeText(this,
"Title: " + c.getString(0) + "\n" +
"isbn: " + c.getString(1) + "\n" +
"Publisher: " + c.getString(2) + "\n" +
"Year: " + c.getString(3) + "\n" +
"Image On Line: " + c.getString(4) + "\n" +
"Image On SD " + c.getString(5) + "\n" ,
Toast.LENGTH_LONG).show();
String imageInSD = c.getString(5);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
myImageView=(ImageView)findViewById(R.id.imageview1);
myImageView.setImageBitmap(bitmap);
}
----------
I'm pretty sure you're setting the second image name to the reviewImageLink (not sure if this is a class variable or what) variable. Instead, try passing both the URL and the String to the AsyncTask. Instead of passing a URL... pass in an Object... where the first one is the URL and the second is the name, and use that in the onPostExecute.
You don't show how ImageLink is set up. But as the filename is constructed from it, I guess your problem has almost nothing to do with the code you showed here.