Getting an image from an HttpResponse - android

I'm attempting to hit a web service to retrieve an image pertaining to an ID I send with the request. The web service returns a jpeg.
I have a few questions:
I want to store this jpeg in my application's SQLite3 database. What column type should I use? A blob?
What data type should I read it in as to store it in the column?
And lastly, how do I take the data from this column and throw it into an ImageView?

I would suggest against using the DB , you can just use the cache folder to store the images ans perform normal file functions on it. Here is some info : http://developer.android.com/guide/topics/data/data-storage.html#InternalCache

Depending on the size of the image, you might want to store it instead on the SDCard (this is what Android does with images ... pictures you take, for example) and store only the Uri of that image in the DB. Small images you can store the bytes in the DB.
This is what I do, and it's worked well.
To create an image from the bytes you can use
Bitmap theImageFromByteArray = BitmapFactory.decodeByteArray( imageByteArray, 0, imageByteArray.length );
imageView.setImageBitmap( theImageFromByteArray );

Related

How can I make array of image from Firebase storage?

I have an idea about the widget that when I click on widget, the text & image will refresh randomly. I have done this with text, but my images are stored on Firebase and I want to take these random images and display them in an ImageView. So how I can do this?
Screenshot of my Firebase Storage:
Screenshot of my App:
As an alternative to #Bernd's answer: You could modify your image names to a standard naming scheme using incremental numbers. You could then retrieve the image URLs dynamically, like so:
Example image names:
image_0.jpg
image_1.jpg
image_2.jpg
image_3.jpg
Some example Java code to generate a random image filepath:
//The amount of images you have stored
int maxImages = 4; //Amount of images
Random random = new Random();
//Randomly generate a filepath to an image
String imageFilePath = "image_" + random.nextInt(maxImages) + ".jpg";
You can then use your generated imageFilePath with FireBase Storage's getDownloadUrl() to retrieve the proper download URL. You can then pass the URL to Glide, Picasso, or another image download library to load it into your ImageView.
Advantages
Only have to use Firebase Storage to achieve your goal
Less overhead on the database, don't have to maintain a list of images there
Disadvantages
You have to control the image names tightly, no custom image names
You have to have a fixed number of images
Could break if you delete an image without changing other image names
Retrieving the URL will throw an exception if the image couldn't be found (e.g. if the random number is out of bounds)
To randomly select an image from Firebase storage, you need to have a list of download url's of the files somewhere. As described in this answer, there is no Api to get a list of these pictures at the moment, so you will have to store the urls of them somewhere.
One possibility for this is to simply add the urls
of the files to Firebase database.
When you want to select a random image, you could go through the database,
and select a random url from this list.
To actually display them in the ImageView, you can use a library like Glide, to make this process easier. The FriendlyPix example App by Firebase, shows how to do this.

Save Image and Text together in database on android

I am working on an Android app like Notepad.
There are two sections.
Text Only
Text with images
A notepad which can only get text from user and save it in db and then retrieve is done.
The another section, will work basically like MS Word.
User can select image from gallery and save it in notepad.
But how can I achieve it? Because I want to store that whole data (image & text) into db as it is. Means suppose user added an image after 2 lines of text. Then app should retrieve it from db in that format only.
Any suggestions? Please help me. Thanks in advance.
The most simple solution would be to define tags or some other form of markup language, that would store that image within a text as a path to file on Disk for example which is imho better alternative than storing it in SQLite but if you insist on database, you can store something like an imageId and keep it the there... However, you are manually doing something, that has already been optimized for you when trying to handle the byte array instead of a file in memory ..
Once you store images in this custom markup language, you can parse it and split the text on chunks between the images which you populate dynamically to some ViewGroup(i.e. LinearLayout) as separate TextViews and ImageViews...
Finally, if you want a solution quickly, you can use some already developed libraries such as this : https://android-arsenal.com/details/1/1696 ... However, this pattern is so common that you can find a great number of libraries that do exactly the thing you are looking for ...
Don't reinvent the wheel if it's not necessary..
You can save the byteArray or uri of images in the database.
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray();
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
Uri uri = Uri.parse(path);
Hope this helps ....

How to save images from server and reuse later

I have an Application and that is live on google, but Now we have plan to change its little working to make it less in size. At the time now its about 60mb and its just due to number of images we have packaged in. Now We have decided to send less embed images in the app built and later let the user download these manually from the server. But I have confusion in couple of things. and these are as following.
How to download the images from server and save them in the device to reuse purpose. I mean let say we have uploaded 10 images on server, user download all of them , now next time if our server has no new images the last 10 images which are saved in devices should be able to reuse and should not be download by the app again.
so this point has three more point
1) How to download and where to download the images
2) If the user has deleted some images downloaded then how to check which images are deleted and to re download them.
3) Is there any way to save the images in a place where user can not see them out side app and not be able to delete them (to eliminate my second point)
Also I have an grid view I am using them to show the image in grid , user click on the image and the real images open in new activity with some info now I have confusion in this also and that is
As we are planning to embed at least 10 images in apk , so we need to show them in the grid (its easy as I am showing them from the app resource folder into the grid view ). But now as we have to download the images from server also , so now How do we populate the images into that grid view and how do we keep track that which image is coming from where either from the resource (as in previous version ,I have just to get it from drawable. but now the things are changed and complicated)
so in short the grid view is mix up of the local app images and the images from the server.
would not it be time consuming to search the last downloaded images from the device and them to display them into a grid view ?
Thanks for reading so long question.
I will try to make it as much clear as possible in step by step:
Create a table in local db (sqlite) and put its name some thing like "Image Paths" with 3 columns, "image_id" , "image_path", "image_name"
When your app launches for the first time after being installed, check if table is empty or not by doing something like this:
// this will return true if the table has no data
public static boolean checkTable(String q){
DataBaseHelper dbh = new DataBaseHelper();
SQLiteDatabase sqldb = dbh.createAndOpenDB();
Cursor cd =null;
try{
boolean isEmpty=false;
cd = sqldb.rawQuery(q, null);
if(cd!=null){
cd.moveToFirst();
if(cd.getInt(0)==0){
isEmpty = true;
}
}
cd.close();
dbh.closeDB();
return isEmpty;}
catch(Exception e){
e.printStackTrace();
if(cd!=null){
cd.close();
dbh.closeDB();
}
return false; } }
If the table is empty then it means either the app is running the first time or the user has deleted the private application data, either way after that you will want to download the whole list of images from server.
When you download images to the device now you should create a separate folder in internal memory which should be private to your app only, to do that:
// write images privately
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
You should then save the name of each image along with its access path to the table that we just created in step 1.
So now accessing those images will be faster and much reliable, if for example you want to update the images from the server. Lets say you have some new images which you want to be synchronized with the device then you should make another table of versions which must be synchronized with the server's version table.. (both must have the same table) So when you check your image_path table in step 2, if the data is found then you should get a list of current versions from the server and match them with your local copy of it. If any version doesn't match then you should update accordingly.
If you want the user to not be able to delete your app's data using the clear data button, then you can hide it using the android:manageSpaceActivity attribute in the manifest file for example:
android:manageSpaceActivity="com.main.slash.LaunchingActivity"
EDIT
After your comments, to create a folder in internal memory privately and save a file in it:
File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal directory/folder;
File imageFile1 = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(imageFile1);
// to get the path of the file you can call the getPath() or getAbsolutePath() methods
String path = imageFile1.getAbsolutePath();
Get images by parsing in bitmap format and store them in your app database, or sdcard.
I think you have downloaded the images, then you should go for saving images to your sdcard memory, with numbering so that you can check them in later launch either present or not.
If not present then download the same image and save to that location with same name.
eg: image_1, image_2, .....image_10. (downloaded images to sd card)
In Activity or wherever you want check if image_1 not present then download and write it with the same filename(file path).
Checking from the sdcard will not consume so much time, wherever you use them like in you GridView.
check link for if need, how to save image from urlto sdcard(external storage):
Android - Save image from URL onto SD card
link to show images from the sdcard to GridView:
http://android-er.blogspot.in/2013/10/gridview-example-load-images-to.html
That's all folks.
Thanks

Android Save EditText with Image

Right now I have a simple App that takes a picture and saves it to a folder. I'm trying to figure out a way to have a user answer questions about each picture (I would just be using EditTexts with that). Is there a way to connect those EditTexts with the image so that when I would open up the image on another page that i could click a button to view the information that was entered along with that image? I have an idea on how to code everything else, just not keeping the edittexts associated with the image. Any ideas would be greatly appreciated!
Thank you!
perhaps you could create a data file alongside the image that has the same name as the image file, but a different extension.
So if you are saving an image called img1.png you save another file alongside it called img1.txt which contains the data you collect from the EditText(s). How you format this data file will depend a bit on how much data you have to store, and what kind of structure the data needs to represent (if any)
Then when you load up a png to display it you'll need to also load up the txt file that shares the same name, and populate the data contained inside to some TextView or something near your ImageView.
Use a database. Make a table that associates images with the data you want. When you display the picture, read the info for that picture from the database and display that as well. Either store the images directly in the db or store them in a folder and use the filename as the primary key in the database table.
There's number of ways to accomplish this. You could use a hashmap where the String is the data they entered and int is the resourceID of the image. For persistent storage, I recommend an SQLite Database that stores the string in a column and the associated image in another.
A few options:
Save a file with the image.. Give it the same name but .txt or something. The file should probably be stored in the location returned by getFilesDir() . Alternatively you could use SharedPreferences.
Use an sqlite database
Save within the exif data of the image. Use the ExifInterface class with setAttribute/getAttribute to save the values.

Technique for Storing Android Contact Icons

I'm wondering what the best way to store a local phone contact's icon is. I'm writing a manager that will allow the user to select contacts for display in a list which now needs contact icon display.
Would storing the icon in a different location on select work or should I try the route of storing the location of the icon and linking to it that way? Can anyone who has went through this already point me in the right direction? I'm using an Sqlite database to store the contacts already.
Any code/links would be very helpful.
Since you are already storing the contacts in an Sqlite db, I'd just add another field to that db that will hold an encoded image.
The way I have gone to solve a similar issue is: I used Base64 for encoding an image into a String and then I store that String wherever I want...
I added one function to the Base64 class to directly encode a Bitmap object for me and return a String, here's the code:
public static String encodeBitmap(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] buf = stream.toByteArray();
return encodeBytes(buf);
}
where encodeBytes(buffer) is already an implemented function of the Base64 class.
This would be a better way of doing it than storing the path to the image, because a user can easily change the path and then your application wouldn't find the picture anymore.
Hope that helps.
First, I'd recommend looking at the Android source and seeing how they do it.
That aside, if the images are smallish, I'd highly recommend creating a proper ContentProvider and storing the images as binary blobs attached to the row using Cursor.getBlob(). See http://developer.android.com/intl/de/guide/topics/providers/content-providers.html#querying for more details.
For larger images, take a look at How to store large blobs in an android content provider?

Categories

Resources