I want to cache some images when downloaded and when again my application starts, it should check if the images are cached so it returns images otherwise null , so I download and cache them again
I tried using LRU Cache http://developer.android.com/reference/android/util/LruCache.html but it didn't work for me , coz its for API level 12, and I am working on 10.
here is that question
caching images with LruCache
What are the other easy adoptable possible solutions to cache
Check out this for storing your files:
Storage options android sdk
okay I did like this
private Bitmap getFile(String fileName) {
Bitmap file = null;
try {
FileInputStream fis;
fis = openFileInput(fileName);
file = BitmapFactory.decodeStream(fis);
fis.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
protected void putFile(Bitmap bitmap, String fileName){
FileOutputStream fos;
try {
fos = openFileOutput(fileName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... params) {
for (int i = 0; i < HomeActivity.globalObj.categoriesList.size(); i++) {
Bitmap b;
b = getFile(HomeActivity.globalObj.categoriesList.get(i).name);
if (b == null) {
b = getImageBitmap(HomeActivity.globalObj.categoriesList.get(i).large_image);
putFile(b, HomeActivity.globalObj.categoriesList.get(i).name);
}
ImageView iv = new ImageView(getApplicationContext());
iv.setImageBitmap(b);
imageViewList.add(iv);
}
Related
How do I load the same picture the user has selected even after the user closes the app?
I currently have the following code which I call in onCreate, but the Bitmap is null every time the user closes the app.
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
File f = new File(directory.getAbsolutePath(), "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Assuming the image was actually saved as profile.jpg and it exists in the imageDir folder, all you need to do to load the image (based on your current usage) is:
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myFile = new File(directory.getAbsolutePath(),"profile.jpg");
if(myFile.exists()){
try {
Bitmap b = BitmapFactory.decodeFile(myFile.getAbsolutePath());
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("MyApp", "The image file does not exist.");
}
}
But if the image is not yet saved or non-existence, then you may need to ask another question that details how you are currently doing it. But this setup will allow you know if that image actually existts.
i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
I am quite new to android. I want to save image to internal memory and later retrieve the image from internal memory and load it to image view. I have successfully stored the image in internal memory using the following code :
void saveImage() {
String fileName="image.jpg";
//File file=new File(fileName);
try
{
FileOutputStream fOut=openFileOutput(fileName, MODE_PRIVATE);
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
}
catch (Exception e)
{
e.printStackTrace();
}
}
using this code image is saved. But when i try to retrieve the image it gives me error. The code used to retrieve the image is :
FileInputStream fin = null;
ImageView img=new ImageView(this);
try {
fin = openFileInput("image.jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = null;
try {
fin.read(bytes);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
img.setImageBitmap(bmp);
But i get a Null pointer exception.
I checked the file is there in internal memory at path :
/data/data/com.test/files/image.jpg
What am i doing wrong please help me out with this. I have gone through a lot of stack questions.
it is because your bytes array is null, instantiate it, and assign size.
byte[] bytes = null; // you should initialize it with some bytes size like new byte[100]
try {
fin.read(bytes);
} catch (Exception e) {
e.printStackTrace();
}
Edit 1: I am not sure but you can do something like
byte[] bytes = new byte[fin.available()]
Edit 2 : here is a better solution, as you are reading Image,
FileInputStream fin = null;
ImageView img=new ImageView(this);
try {
fin = openFileInput("image.jpg");
if(fin !=null && fin.available() > 0) {
Bitmap bmp=BitmapFactory.decodeStream(fin)
img.setImageBitmap(bmp);
} else {
//input stream has not much data to convert into Bitmap
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Helped by - Jason Robinson
I have trouble with saving images on sd card. I can see the file on the sd card but file is empty (size 0). I tried saving it on the phone memory and it works fine. Here is my code.
Imagewritter {
public static boolean writeAsJPG(Context context, Bitmap bitmap,
String filename) {
filename = filename + ".jpg";
File path = Environment.getExternalStorageDirectory();
File f = new File(path, filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}
bitmap.compress(CompressFormat.JPEG, quality, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
Log.d(TAG, "error closing");
e.printStackTrace();
}
}
here is the code where the bitmap comes from.
DrawingView = (drawing) findViewById(R.id.drawing_view);
drawingBitmap = (Bitmap) DrawingView.getBitmap();
String idName = timeStampText;
//save Image as JPG
ImageWritter.writeAsJPG(getApplicationContext(), drawingBitmap, idName);
i think u have to add these permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Get the image in byte array & check the size of that byte array.. I think you getting 0 size byte array.....
The only problem here is that I have two lines for writing the file. Using FileOutputStream and OpenFileOutput. Just remove these lines and it'll be fine.
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}
This is my first attempt at serializing/deserializing objects on any platform and, to put it mildly, I'm confused.
After implementing Serializable to my game object I output it to a file thus:
public void saveGameState(){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(theGame);//theGame is an instance of the custom class
//TGame which stores game info.
byte[] buf = bos.toByteArray();
FileOutputStream fos = this.openFileOutput(filename,
Context.MODE_PRIVATE);
fos.write(buf);
fos.close();
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
}
File f =this.getDir(filename, 0);
Log.v("FILE",f.getName());
}
This seems to work, in that I get no exceptions raised. I can only know for sure when I deserialize it. Which is where things go pear shaped.
public God loadSavedGame(){
TGame g=null;
InputStream instream = null;
try {
instream = openFileInput(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
I got the basis of this code from here Android Java -- Deserializing a file on the Android platform and tried to modify it for my app. When running I get
05-31 23:30:45.493: ERROR/copybit(1279): copyBits failed (Invalid argument)
When the output should be loaded and the saved game start up from when it was saved.
Any help would be appreciated.
The error you've shown is not at all related to serialization: its actually a video display error. I'd suggest looking at the object BEFORE you serialize to make sure its not null, and I'd also suggest serializing to a file on the SD card to make sure you actually had data output (so use new FileOutputStream("/mnt/sdcard/serializationtest") as the output stream and new FileInputStream("/mnt/sdcard/serializationtest") as the input stream) while you are debugging; you can switch back to the context methods after it works, but make sure your sdcard is plugged in while you are doing this.
Finally, modify your logging to look like this:
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT FOUND):"+e.getMessage(), e);
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+e.getMessage(), e);
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
android.util.Log.e("DESERIALIZATION FAILED (IO EXCEPTION):"+e.getMessage(), e);
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
and see what error gets returned. I expect the serialization is failing somehow.
To seralize or deserialize anything you can use SIMPLE api. It is very easy to use. Download the file and use it in your program
Have a look here
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#deserialize
Thanks Deepak
I have created below class to do the save and retrieve object.
public class SerializeUtil {
public static <T extends Serializable> void saveObjectToFile(Context context, T object, String fileName){
try {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(object);
os.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static<T extends Serializable> T getObjectFromFile(Context context, String fileName){
T object = null;
try {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
object = (T) is.readObject();
is.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
public static void removeSerializable(Context context, String filename) {
context.deleteFile(filename);
}
}