I am downloading requested image from my server , this image is successfully displayed after downloading but when i try to store the same image on my SD card it returns null.
Here is my code for downloading image and saving it.I am getting null on a call to bitmap.compress()
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image.png";
File file = new File (myDir, fname);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
message_bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//write the bytes in file
FileOutputStream fo;
try {
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
message_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}*/
}
static public Bitmap downloadBitmap(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + e.toString());
} finally {
if (client != null) {
}
}
return null;
}
I think you are pretty close there. How about something similar to the below which downloads and saves an image:
try {
img_value = new URL("your_url");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String filename = "your_filename.jpg";
File file = new File(dir, filename);
if (file.exists()) {
try{
file.delete();
}catch(Exception e){
//sdcard plugged in
}
}
try {
FileOutputStream out = new FileOutputStream(file);
mIcon1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();//will occur if the phone is plugged in
}
Related
How would i know if i downloading of images failed?
What happens is that i download the image url first, and from there get the image filename to store to my database. Then have two methods to download from the url, and save is as the filename. Btw, they are being called by a method that is being called by an AsyncTask.
Here are the two methods (that are handed down by my senior) that is handles the download of the image files:
private void imageProcessing(String url, String filename) {
String root = Environment.getExternalStorageDirectory().toString();
// String root1= getResources().getIdentifier(name, defType, defPackage)
File myDir = new File(root + "/arson/images");
File nomedia = new File(myDir, ".nomedia");
if (!nomedia.exists()) {
Log.wtf("nomedia not exists", nomedia.getAbsolutePath().toString());
try {
nomedia.createNewFile();
} catch (IOException e1) {
Log.e("NEW FILE CREATION", e1.toString());
e1.printStackTrace();
}
} else {
Log.wtf("nomedia exists", nomedia.getAbsolutePath().toString());
}
File file = new File(myDir, filename);
if (file.exists()) {
file.delete();
}
try {
Bitmap bitmap = downloadBitmap(url);
myDir.mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("BITMAP PROCESS", e.toString());
}
}
public static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
System.setProperty("http.keepAlive", "false");
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or
// IllegalStateException
getRequest.abort();
} finally {
if (client != null)
client.close();
}
return null;
}
Thanks in advance!
There are two kind of possible issues here.
1) HTTP Status Code is not 200 : You are returning null if this happens, and when you get null you can know there has been a problem downloading.
2) HTTP Status Code is 200 but file download fails : You will either have an exception here, or none at all. If you have an exception you are already catching it. For the other case where there is no exception you have to change your implementation a little. You will have to save the downloaded file first (temp file), read the contentLength and verify that it matches with what you got from the server. If the contentLength is correct, you can then use BitmapFactory to read the file from the device.
I want to retain some strings even when i clear my app data so i am using text files saved in sd card.
I am using sd card files to store myStrings and read them at run time. but each and every time readfile return null.
following is my code:
protected void writeToFile(String data, String fileName) {
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
if(dir.mkdir())
{
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
protected String readFromFile(String fileName, String defaultValue) {
String ret = "";
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
File file = new File(dir.getAbsolutePath() + "/"+fileName);
try {
//InputStream inputStream = openFileInput("/sdcard/"+fileName);
FileInputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
/*if((receiveString = bufferedReader.read) != null){
stringBuilder.append(receiveString);
}*/
String line="";
int c;
while ((c = bufferedReader.read()) != -1) {
line+=(char)c;
//counter++;
}
stringBuilder.append(line);
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
if (ret.equals("")) {
ret=defaultValue;
}
return ret;
}
try to add the "file:///" suffix before the Uri
I've some problems with InputStream after download an image. downloadImages method return an InputStream that i write in a file. But there is an exception in inputStreamToFile method: java.io.IOException: BufferedInputStream is closed. Here the codes:
Download
public static InputStream downloadImages(String imageUrl) {
HttpURLConnection httpConn = null;
String urlBase = imageUrl;
if(D) Log.d(TAG, "downloadImages(): url request: " + urlBase);
try {
URL url = new URL(urlBase);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(SystemConstants.TIMEOUT_CONNECTION);
httpConn.setReadTimeout(SystemConstants.SOCKET_CONNECTION);
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
return inputStream;
}
} catch (IOException e) {
Log.w(TAG, "downloadImages(): exception: " + e);
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(httpConn != null) httpConn.disconnect();
}
return null;
}
From IS to file
public static void inputStreamToFile(InputStream is) {
if(D) Log.d(TAG, "inputStreamToFile() called");
OutputStream outputStream = null;
try {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Utils.isExternalStorageRemovable() ?
Utils.getExternalCacheDir(App.getContext()).getPath() :
App.getContext().getCacheDir().getPath();
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(cachePath + File.separator + "vr"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
if(D) Log.d(TAG, "read called");
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
if(D) Log.d(TAG, "inputStreamToFile(): outputStream is not null");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Put your logcat.Then only we can identify the errors,bugs,etc
I am trying to fetchg data from server like MP3 files, video files, etc. in my application. The application should show the list of video files received from the server.
How can I do this?
/** this function will download content from the internet */
static int writeData(String fileurl, boolean append, String path,
String filename, Activity mContext) throws CustomException {
URL myfileurl = null;
ByteArrayBuffer baf = null;
HttpURLConnection conn = null;
String mimeType="";
final int length;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myfileurl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(100000);
length = conn.getContentLength();
mimeType=conn.getContentType().toString();
System.out.println("Extension..."+mimeType);
if(mimeType.equalsIgnoreCase("application/vnd.adobe.adept+xml") || mimeType.equalsIgnoreCase("text/html; charset=utf-8"))
return 0;
if (length > 0) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((byte) current);
mBufferError=false;
} catch (Exception e){
// TODO: handle exception
mBufferError=true;
e.printStackTrace();
throw new CustomException("### memory problem ", "Buffer Error");
}
}
}
} catch (IOException e) {
mBufferError=true;
e.printStackTrace();
}
try{
if(conn.getResponseCode()==200 && mBufferError==false)
{
path = path + "/" + filename;
boolean appendData = append;
FileOutputStream foutstream;
File file = new File(path);
boolean exist = false;
try {
if (appendData)
exist = file.exists();
else
exist = file.createNewFile();
} catch (IOException e) {
try {
return 1;
} catch (Exception err) {
Log.e("SAX", err.toString());
}
}
if (!appendData && !exist) {
} else if (appendData && !exist) {
} else {
try {
foutstream = new FileOutputStream(file, appendData);
foutstream.write(baf.toByteArray());
foutstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new CustomException("### I/O problem ", "I/O Error");
}
return 1;
}
once download complete search the file with extension(.3gp) for video
hope it helps
Check this link,
https://stackoverflow.com/search?q=how+to+download+mp3+%2Cvideos+from+server+in+android
Try this code
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();
I am new in Android.
I am downloading images from the internet in the ListView .I getting the url in the file object but when I send it into the Bitmap object the bitmap object is return null means image is not loaded into the bitmap object.please reply me. the code is here:
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// here in f i getting image url
// here in bitmap the url is not loaded & get null
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if(bitmap != null) return bitmap;
// Nope, have to download it
try {
bitmap =
BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void writeFile(Bitmap bmp, File f) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try { if (out != null ) out.close(); }
catch(Exception ex) {}
}
}
I do not think you are downloading properly the bitmap.
CODE
This is a function I created that will take a url from you and it will return a drawable!
It will save it to a file and get it if it exists
If not, it will download it and return the drawable.
You can easily edit it to save file to your folder instead.
/**
* Pass in an image url to get a drawable object
*
* #return a drawable object
*/
private static Drawable getDrawableFromUrl(final String url) {
String filename = url;
filename = filename.replace("/", "+");
filename = filename.replace(":", "+");
filename = filename.replace("~", "s");
final File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + filename);
boolean exists = file.exists();
if (!exists) {
try {
URL myFileUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
try {
if (file.createNewFile()){
//
}
else{
//
}
FileOutputStream fo;
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
BitmapDrawable returnResult = new BitmapDrawable(result);
return returnResult;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
else {
return new BitmapDrawable(BitmapFactory.decodeFile(file.toString()));
}
}
Only thing I can think of here is that you're missing INTERNET permission in your manifest.
Try adding <uses-permission android:name="android.permission.INTERNET" /> in your AndroidManifest.xml if it's not there yet