I have this function that downloads and saves images in device -
public void DownloadFromUrl(String WebURL, String fileName) {
try {
URL url = new URL(WebURL);
file = new File(context.getFilesDir() + fileName+".jpg");
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
If I supply an https URL, it cannot save the image. Any pointers on how to download and save https images ?
I hope this link will help you. Uploading/Downloading Pictures by Tonikami.
https://www.youtube.com/playlist?list=PLe60o7ed8E-Q7tqKNPnWFdUoeniqH_-A9
Just use Picasso or Glide. It is super easy to use. And the best part is that it does automatic disk and memory caching, so you do not have to worry about anything.
Picasso - check out this link.
OR
Glide - check out this link.
The only mistake I made above is that I was trying to download and save large images when connectivity was slow. Some of my images are around 5-10 MB. Otherwise the code is fine.
Related
What i have:
I have uploaded a .json file to the Dropbox of my account I have
made it public
What i am trying to do:
I want to download the file to my RAW folder of my android project
I am familiar with AsyncTask and HttpClient but what
methodology(steps) should I follow to download the file?
I tried searching for a similar question in stackoverflow but couldn't find one so posting a question myself
You cannot download a file into "assets" or "/res/raw". Those get compiled into your APK.
You can download the file to your apps internal data directories. See Saving Files | Android Developers.
There are plenty of examples and libraries to help you with the download. The following is a static factory method you could use in your project:
public static void download(String url, File file) throws MalformedURLException, IOException {
URLConnection ucon = new URL(url).openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) ucon;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
bis.close();
}
}
Then, to download a file from Dropbox:
String url = "https://dl.dropboxusercontent.com/u/27262221/test.txt";
File file = new File(getFilesDir(), "test.txt");
try {
download(url, file);
} catch (MalformedURLException e) {
// TODO handle error
} catch (IOException e) {
// TODO handle error
}
Please note that the above code should be run from a background thread or you will get a NetworkOnMainThreadException.
You will also need to declare the following permission in your AndroidManifest:
<uses-permission android:name="android.permission.INTERNET" />
You can find some helpful libraries here: https://android-arsenal.com/free
I personally recommend http-request. You could download your dropbox file with HttpRequest like this:
HttpRequest.get("https://dl.dropboxusercontent.com/u/27262221/test.txt").receive(
new File(getFilesDir(), "test.txt"));
I'm downloading an Image using this code:
// Download AVATAR
try {
File avatar = new File(Environment.getExternalStorageDirectory() + "/Android/data/carl.fri.fer.omegan/avatar.jpg");
prefs.edit().putString("loginUser", json.name).commit();
prefs.edit().putInt("loginMatter", json.darkmatter).commit();
if (!avatar.exists()) {
Log.i("AVATAR", "Downloading user avatar...");
URL url = new URL("Valid URL");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(avatar);
fos.write(baf.toByteArray());
fos.close();
}
else Log.i("AVATAR", "The user avatar already exists!");
} catch (IOException e) { System.out.println("Error downloading avatar: " + e); }
And then I try to show this image using this code:
File usrAvatar = new File(Environment.getExternalStorageDirectory() + "/Android/data/carl.fri.fer.omegan/avatar.jpg");
if(usrAvatar.exists()) {
Bitmap avatarBmp = BitmapFactory.decodeFile(usrAvatar.getAbsolutePath());
userAvatar.setImageBitmap(avatarBmp);
}
The problem appears here:
userAvatar.setImageBitmap(avatarBmp);
Android 4.0.4: Error type: NullPointerException.
Android 2.3.5: Error type: ImageView not showing image but no error appears.
1- The ImageView userAvatar is right because I can show and image from the drawable folder.
2- The image I want to show is downloaded successfully because using a file manager I can find it on the specified folder and file name.
3- The image is not corrupted because I can open it using any image viewer.
So, which can be the problem? It's driving be crazy!
Any help will be appreciated.
Thank you in advantatge!
try the following code:
ImageView bmImage;
FileInputStream instream = new FileInputStream("/sdcard/Pictures/Image.png");
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
textView.append("\r\n" + byteImage1+"\r\n");
bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage1, 0, byteImage1.length));
textView.append("\r\n" + byteImage2+"\r\n");
I've read some posts about this, but they don't seem to work.
I have an online picture, http://sivo.site90.com/dag_1.jpg
I want to download the picture to the SD card (sdcard/data/data/com.myapp),
show an image view of the saved file, and have the file available later from the SD card for offline viewing.
Does anyone how I can do this?
I had a similar requirement. But instead of saving the image in the sd card. I saved it into the sqlite database.
This is the code I use to get the image and save to the bytearray
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
Later you can save this byte array in the database as the type blob.
In this way, user cant delete your image from the sd card.
You can set the byte array to the imageview like this
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));
I'm a newbie at Android, and developing my first app.
I'm using the following code to download 10 images from my website
private class DownloadImages extends AsyncTask<Integer, Integer, Integer> {
#Override
protected Integer doInBackground(Integer... pic_ids){
int count = pic_ids.length;
for (int i = 0; i < count; i++) {
// download the image from website ...
String url = "http://www.mysite.com/pic.php?pid=" + pic_ids[i];
DownloadFromUrl(url, pic_ids[i] + ".jpg");
publishProgress((int) (i + 1));
}
return count;
}
}
public void DownloadFromUrl(String imageURL, String fileName){
try {
URL url = new URL(imageURL);
File file = new File(getFilesDir() + "/" + fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8192);
ByteArrayBuffer baf = new ByteArrayBuffer(128);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e);
}
}
The "DownloadImages" is passed an array of 10 ID's. All are handled (I have Log.d statements in between to check), however, only 1 out of 2 actually gets downloaded. Not in a random way: the first one is downloaded, the second one not, the third one is downloade, the fourth not etc. That means: The files are all written to the phone/emulator, but those that "fail" are empty.
When I start it again with only the 5 remaining images (those that were not downloaded the first time), the same thing happens (1st one downloaded, 2nd one not, ...)
I don't see an error in the logs.
Adding a check for baf.length shows that this is 0 for those files that fail.
Any idea ?
This is long past due but I was having the same issue a few months ago. The strange thing was it only happened while connecting with SSL.
I eventually had to implement a checker to see if it truly downloaded and if not tried again (terminated after the second attempt at each file).
In my app when the splash screen gets started I am downloading an image from the URL. I want to use the same image in another activity of my app. Following is my code to download the image
public void DownloadImage(String fileName)
{
try
{
URL url = new URL(main.BannerImage); //you can write here any link
File file = new File(fileName);
Log.e("file ",""+file);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("Error: ","" + e);
}
How can I get the image as a background source in another activity please help me friends
You can save the image in SDCard and the path can be send to next activity using
intent.putExtras("filename","filepathname");
and get in the next activity using
getIntent().getExtras().getString("filename")
from this you can get filepath from previous activity and you can get the image from specific filepath.
You can convert the image into bitmap and and pass it to next activity using Parcelable like
Bundle extras = new Bundle();
extras.putParcelable("data",bitmap);
Intent intent=new Intent(currentActivity.this,nextImage.class);
intent.putExtras(extras);
startActivity(intent);
finish();
in nextactivity you can get bitmap as
Bitmap image=getIntent().getExtras().getParcelable("data");