- Android: How to load Image from URL in ImageView?
- Project Description
- Environment Used
- Prerequisites
- Android Project
- strings.xml
- XML layout file
- Activity
- AndroidManifest.xml
- Output
- Project Folder Structure
- Android Loading Image from URL (HTTP)
- Required Classes
- Related Posts
- Android Integrating PayTM Payment Gateway – ECommerce App
- Android Integrating Google’s reCAPTCHA in your App
- Android Content Placeholder Animation like Facebook using Shimmer
- Learn2Crack
- Android Load Image from Internet (URL) – Example
- Лучший способ загрузки изображения с url в Android
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
Android: How to load Image from URL in ImageView?
Project Description
- In this tutorial, we will see how to load an image from URL into Android ImageView.
- For downloading the image from URL and loading it in ImageView, we use AsyncTask.
Environment Used
- JDK 6 (Java SE 6)
- Eclipse Indigo IDE for Java EE Developers (3.7.1)
- Android SDK 4.0.3 / 4.1 Jelly Bean
- Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
- Refer this link to setup the Android development environment
Prerequisites
Android Project
Create an Android project and name it as “ImageViewFromURL“.
strings.xml
Open res/values/strings.xml and replace it with following content.
XML layout file
This application uses XML layout file (main.xml) to display the ImageView.
Open main.xml file in res/layout and copy the following content.
Activity
In src folder, create a new Class and name it as “ImageViewFromURLActivity” in the package “com.theopentutorials.android.views” and copy the following code.
From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below.
- Whenever we need to perform lengthy operation or any background operation we can use Asyntask which executes a task in background and publish results on the UI thread without having to manipulate threads and/or handlers.
- In onCreate(), we create and execute the task to load image from url. The task’s execute method invokes doInBackground() where we open a Http URL connection and create a Bitmap from InputStream and return it.
- Once the background computation finishes, onPostExecute() is invoked on the UI thread which sets the Bitmap on ImageView.
Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client.
For Gingerbread and later, HttpURLConnection is the best choice.
AndroidManifest.xml
Define the activity in AndroidManifest.xml file. To access internet from Android application set the android.permission.INTERNET permission in manifest file as shown below.
Output
Run your application
Project Folder Structure
The complete folder structure of this example is shown below.
Источник
Android Loading Image from URL (HTTP)
I am writing this tutorial as lot of people are asking me about loading an image into imageview. Just by adding url to ImageView won’t load directly. Instead we need to store the image into cache (temporary location) and attach to ImageView. This can be achieved just by calling couple of lines and don’t forget to add required classes to your project.
1. Create a new project in Eclipse IDE by navigating to File ⇒ New ⇒ Android Project and fill the required details.
2. Inorder to load images from an url we first need to store the image in a temporary location and once it is downloaded it should be added to ImageView. To create a temporary file we need to access device external storage. Add required permission to AndroidManifest.xml file.
To access internet required permission is – INTERNET
To access external storage required permission is – WRITE_EXTERNAL_STORAGE
3. For testing purpose create a simple ImageView in your main.xml file
4. Open your main activity and type the following code. Whenever you wan’t to show an image from url just call the following code.
5. Add following classes in your project and run the project.
Required Classes
ImageLoader.java
FileCache.java
Utils.java
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]
Related Posts
Android Integrating PayTM Payment Gateway – ECommerce App
Android Integrating Google’s reCAPTCHA in your App
Android Content Placeholder Animation like Facebook using Shimmer
hello, thank you for tutorial. Unfortunately, it works for me only on emulator and when i install it on my phone, images won’t load. Why does this happen?
and I need to tell that i have 83 mb of free memory on SD card and 50 mb free internal memory
Can Someone help me how can i integrate progressbar in this code? please!
realy thanks man… works fine…
There is a problem with the ImageLoader class. You see, when I added the BitmapFactory.Options o2 under decodeFile(File f) method, I get an “Unreachable Code” error status. What should I do?
no image will be show only loader image is shown help me whats the problem
Raise the REQUIRED_SIZE.
This tutorial is the worst! It is due by updates, instead of the image loaded properly from the URL, I got corrupted image as a result. Look at my sample.
hello..i have to load images & and data from webservices…can u plz help me….
this is what you want
@pratik butani. how to load info like(username ,intrest,gender ,,) in this code
u can use universal image loader library for that…………….
I want to display image in ListVIew From PHP Server or web server .
But I need to set my Enulator HeapSize more than 32 MB. It Generate Errors.
Can I Use Above Code to Display Image in List View From Server.
Help Me.
I am your website great FAN.
Hi
this tutorial is so good
i read about a lib for developer games in android [libgdx]
can you do tutorials about this?
i want to show image in large size so i replace _s by _n but it save it as small,as follow:
String _n=_s.replace(“_s.jpg”, “_n.jpg”);
imageLoader2.DisplayImage(_n, picture);
plz could any one help me?
break the json into pices until you get the url
@anonim …..plzzzz explain how to code to get (username ,…gender,…etc) i m also using json webservic url . aftr login
Hi Ravi
This tutorial is very helpful to me please post the dynamic grid view (Images from server) at least please give me a sugeestions
Please give me code to display multiple images from MYSQL DB with help of php webservice
hi did u got solution of that image blurred .
With the same code when i replace image url it throws FileNotFound Exception . i m stuck with it. Any idea?
sir i have same problem
and i have already add this permision
Thnaks this is very helpful..
Hi Ravi… Its Fantastic Tutorial.. Thanks a lot.
Here I want to Update Image directly in My Folder, how can i update without passing ImageVIew object.
i have tried like this:
It’s giving me Error…
what can i do… Please Reply me…
Hello sir i am getting too many redirects exception please help me out.
hi ravi …great tutorial ….thankz for this..
then can you provide the API php code for how can i add image to my database and retrieve from it and send to my android app using json…..
Hi Ravi, I haven’t tried this yet, but I want to know if I can use this for populating listview with images? Thanks!
hi ravi …can i also use this .code to show profile information(user name,intresrt,gender…user_image….) aftr login……..from the webservice
Hi Ravi,
How can i set size image from your project, image downloaded and show on device too small than this link:
Thanks so much
That would be nicer if you actually wrote this code.
Hi, thanx for the good tutorial but i want to load multiple images ho to do that?
Pls help me out!
Why i use this link:
above sample can’t load image, return bitmap=null;
Reading image from URL can be performed inside AsynTask as it should not affect the current Activity. Using AysnTask will run downloading image from URL as separate thread.
Regards,
Udhay
http://programmerguru.com
Hi, How to store the Images in internal memory of the phone? In this tutorial we are using External memory for cache
hi , The tutorial helped me a lot…
I have one question though.. Where can I change the size of the image which is downloaded?
did not works with images in a listview
GREAT TUTORIAL i use it to my app – its work perfect!:)
i m asking your help guys
i use my personal String url – JSON that i downloads about 500 images from my Json!
when i scroll the list view fast i
MUST HAVE A SPINNER PROGRESS BAR IN EVERY ROW IN THE LIST VIEW UNTIL THE IMAGE SHOW/COMPLIT –
PLEASE HELP ME WITH THIS
This might help
hi. What is R.drawable.loader? I ask because my program does not recognize it
It is an image name exists in the drawable folder
Its working but i am unable to understand this code. It would be lot better if you explain the working of this project.
Thanks
nice this is so good
Hi Ravi, where do i need to recycle the bitmap? im having trouble whenever i re-open my app using these codes. it says out of memory. thanks
Hi, may i know what is the R.drawable.loader. If it was a code/ image may i have it cause i dont have it on my drawable folder. Thanks in advance.
Got it, just an image.
Im using a fragment and this how i use it:
ImageLoader imgLoader = new ImageLoader(getActivity().getApplicationContext());
public void DisplayImage(String url, int loader, ImageView imageView)
<
stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
<
queuePhoto(url, imageView);
imageView.setImageResource(loader);
>
>
And im getting an error when i call the java class. What is the problem on my code?
ImageLoader imgLoader = new ImageLoader(getActivity() );
hi ravi i want to know ….i want to set image in circle …i m using this code …..so whare to edit ..what to edit in code…..plzzzz rply fast
Very helpful, thanks
i ravi i m using this code its working i have i query ….i want to display image in size as i want …….can u tell me how to increse/decrease size of image which is comming from url
i ravi i m using this code its working i have i query ….i want to display image in size as i want …….can u tell me how to increse/decrease size of image which is comming from url….plzz reply fast
What if I want to make the extension of string image_url automatically detect whether .jpg or .png?
// Image url
String image_url = “http://api.androidhive.info/images/sample.jpg”; // or png?
I’m confused with this function”boolean imageViewReused(PhotoToLoad photoToLoad)”,could you tell me what it is used for?
Источник
Learn2Crack
Android Load Image from Internet (URL) – Example
Sometimes you may need to load an Image from URL in your Android app. If you are searching for a way, this tutorial shows you how to do this with less effort.
Here I have created an Android Studio project with package com.learn2crack.loadimageurl also Activity as MainActivity and layout as activity_main.
Adding Required Permissions
We need to add Internet permission in our AndroidManifest.xml.
Our activity layout has a Button and an ImageView to display the image.
Loading image via the Internet is time-consuming and if done in the main thread it makes the UI unresponsive . So we use AsyncTask to do this in a background thread. The decodeStream() method of the BitmapFactory class is used to load the image. We create a Listener interface to pass the image to Main Activity. The onImageLoaded() method will be called if the image is fetched successfully. The onError() method will be called if an error occurs.
The MainActivity implements the Listener interface. The fetched bitmap is set to ImageView using setImageBitmap() method. If an error occurs a Toast is displayed.
Try this in an Emulator or your own device.
Complete Project Files
You can download the complete project as zip or fork from our Github repository.
Note :
Last Updated On : Oct 15, 2016
Источник
Лучший способ загрузки изображения с url в Android
Я использую ниже метод для загрузки одного изображения из URL
Иногда я получаю исключение outofmemory.
Я не могу исключить исключение из памяти. Приложение закроется. Как предотвратить это?
Есть ли лучший способ загрузки изображений, который также быстрее?
ОТВЕТЫ
Ответ 1
Попробуйте использовать это:
И для проблемы OutOfMemory:
Ответ 2
Я использую эту библиотеку, это действительно здорово, когда вам приходится иметь дело с большим количеством изображений. Он загружает их асинхронно, кэширует их и т.д.
Что касается исключений OOM, использование этого и этого класса резко сократило их для меня.
Ответ 3
Ответ 4
вы можете скачать изображение Asyn task используйте этот класс:
и назовите это так:
Ответ 5
Вы можете использовать функцию ниже, чтобы загрузить изображение с URL.
Смотрите полное объяснение здесь
Ответ 6
Добавьте эту зависимость для сети Android в свой проект
После запуска этого кода Проверка памяти телефона Вы можете увидеть там папку — ИзображениеПроверьте внутри этой папки, вы видите там файл изображения с именем «image.jpeg»
Ответ 7
Исключение OOM можно было бы избежать, следуя официальному руководству загрузить большое растровое изображение.
Не запускайте свой код в потоке пользовательского интерфейса. Используйте AsyncTask, и все будет в порядке.
Ответ 8
OUTPUT
Ответ 9
Шаг 1. Объявление разрешения в манифесте Android
Первое, что нужно сделать в своем первом Android-проекте, — это указать необходимые разрешения в файле ‘AndroidManifest.xml.
Для загрузки изображения Android с URL-адреса нам необходимо разрешение на доступ к Интернету для загрузки файла, чтения и записи во внутреннее хранилище для сохранения изображения во внутреннем хранилище.
Добавьте следующие строки кода в верхней части тега файла AndroidManifest.xml:
Шаг 2. Запросите требуемое разрешение у пользователя
Android позволяет запускать каждое приложение в песочнице. Если приложению требуется доступ к определенным ресурсам или информации за пределами этой изолированной программной среды, оно должно запросить разрешение у пользователя.
Начиная с Android 6.0, Google хочет, чтобы разработчики запрашивали разрешение у пользователя из приложения, чтобы узнать больше о разрешениях, прочитайте это.
Поэтому для загрузки изображения Android с URL-адреса вам потребуется запросить чтение хранилища и запись
Для этого мы будем использовать следующие строки кода, чтобы сначала проверить, предоставлено ли пользователю необходимое разрешение, а если нет, то мы запросим разрешение на чтение и запись в хранилище.
Мы создавали метод la Downlaod Image, вы можете просто вызывать его везде, где вам нужно загрузить изображение.
Теперь, когда мы запросили и получили разрешение пользователя, чтобы начать загрузку образа Android с URL-адреса, мы создадим AsyncTask, поскольку вам не разрешено запускать фоновый процесс в главном потоке.
В приведенных выше строках кода создается URL-адрес и растровое изображение, с использованием BitmapFactory.decodeStream файл загружается.
Путь к файлу создается для сохранения изображения (мы создали папку с именем AndroidDvlpr в DIRECTORY_PICTURES), и загрузка инициализируется.
После загрузки файла MediaScannerConnection вызывается для чтения метаданных из файла и добавления файла к поставщику медиа-контента, чтобы изображение было доступно для пользователя.
В приведенных выше строках кода мы также создали метод showToast() для отображения Toast. полный код здесь:
Ответ 10
Сначала объявите разрешение в манифесте Android: —
MainActivityForDownloadImages.java
DownloadService.java
Ответ 11
Я все еще изучаю Android, поэтому я не могу предоставить богатый контекст или причину моего предложения, но это то, что я использую для извлечения файлов из https и локальных URL-адресов. Я использую это в своем отчете onActivity (как для съемки, так и для выбора из галереи), а также в AsyncTask для извлечения https-адресов.
Источник