Hi i am trying to recursively download the images but i am unable to.
It only downloads the first image! does any one know why?
this is my code to download, I did a log to check if there are items in my list and yes, there are 20:
Log.d("imageList.size",String.valueOf(imageList.size()));
try
{
for (int i=0; i<=imageList.size(); i++)
{
String image= imageList.get(i);
Log.d("imageList.get(0)",image);
String filename = String.valueOf(image.hashCode());
Log.v("TAG FILE :", filename);
File f = new File(cacheDir, filename);
// Is the bitmap in our cache?
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if (bitmap != null)
return bitmap;
else {
// Nope, have to download it
try {
bitmap = BitmapFactory.decodeStream(new URL(image)
.openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Log.v("FILE NOT FOUND", "FILE NOT FOUND");
return null;
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
There seems to be a problem with your for loop, it is exiting on the first iteration of the loop, check your braces and ensure that you have the braces setup the way you intend it and the logic makes sense. You should NOT return until your for loop is done.
Line: 25 in your code, do not return before the loop ends.
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 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 am working on an Android Application which needs to implement the Bluetooth functionality. It needs to receive an image from an external h/w device, and then save that byte array to SD card as an image file.
Here is my code:
public void run(){
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[4096];
//CREATE IMAGE FILE
File test=new File(Environment.getExternalStorageDirectory(), "test.jpg");
if (test.exists()) {
test.delete();
}
try {
fos = new FileOutputStream(test.getPath());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
/*mEmulatorView.write(buffer, bytes);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BlueTerm.MESSAGE_READ, bytes, -1, buffer).sendToTarget();*/
//receivedData = new String(buffer);
receivedData=new String(buffer)
//WRITE BYTES TO FILE
try {
fos.write(buffer);
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
/*
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeByteArray(buffer , 0, buffer.length);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if(bitmap != null)
testModeOnScreen.saveBitmapToSdcardAndEmail(bytes, bitmap);
*/}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My problem is that I am not getting any exception or crashes, but I am getting a corrupted image file.
There seem to be multiple issues here. For starters, garbage at the buffer tail, "Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected":
http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read()
Also, you may happen to need to use the bitmap functionality from Android.
Look how they exchange bitmaps here:
http://kamrana.wordpress.com/2012/05/12/sending-images-over-bluetooth-in-android/
And how they save to a file:
Save bitmap to file function
http://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream)
You could find it easier hacking together those building blocks than reinventing them.
check this solution;)
String TAG="IMG";
File path = Environment.getExternalStoragePublicDirectory(("/mnt/exSdCard/RecievedIMAGE"));
File file = new File(path, "test.jpg");
BufferedInputStream bufferedInputStream = null;
try {
// Make sure that this path existe if it is not so create it
path.mkdirs();
bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream os = new FileOutputStream(file);
final byte[] buffer = new byte[2048];
int available = 0;
while ((available = bufferedInputStream.read(buffer)) >= 0) {
os.write(buffer, 0, available);
}
bufferedInputStream.read(buffer);
bufferedInputStream.close();
os.close();
Log.d(TAG, "success" + buffer);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
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);
}
I need to create a bitmap from sdcard images so after getting uri of image i am getting byte data by opening inputStream as follows
public byte[] getBytesFromFile(InputStream is)
{
byte[] data = null;
ByteArrayOutputStream buffer=null;
try
{
buffer = new ByteArrayOutputStream();
int nRead;
data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1)
{
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
} catch (IOException e)
{
return null;
}
finally
{
if(data!=null)
data = null;
if(is!=null)
try {
is.close();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if(buffer!=null)
{
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer = null;
}
System.gc();
}
after this i am just creating bitmap of that data by following code
byte[] data = getBytesFromFile(is);
Bitmap bm= BitmapFactory.decodeByteArray(data, 0, data.length);
but it gives me outofmemory error. many peoples guide me to check for memory leakages but, this is the first step in my app., i mean thru intent filter i start my app from gallery menu option "share" which invokes my app with the image uri..
plz guide me guys if i am wrong... and also this exception comes on the devices which have high resolution images(size excceds 1MB), but any how it should create Bitmap...
Try to use the BitmapFactory.decodeStream() method instead of first loading the bytearray into memory. Also check out this question for more info on loading bitmaps.