Android imageview load from url

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.

Источник

Как загрузить ImageView по URL-адресу в Android? [закрытый]

Как вы используете изображение, на которое ссылается URL в ImageView ?

23 ответов

убедитесь, что у вас есть следующие разрешения установить в свой AndroidManifest.xml для доступа в интернет.

сначала вам нужно загрузить изображение

затем используйте Imageview.setImageBitmap для установки растрового изображения в ImageView

1. Пикассо позволяет без проблем загружать изображения в вашем приложении-часто в одной строке кода!

Использовать Gradle:

только одна строка кода!

2. скольжения библиотека загрузки и кэширования изображений для Android, ориентированная на плавную прокрутку

использовать Gradle в:

// для простого просмотра:

3. фреска — это мощная система для отображения изображений в Android приложения.Fresco заботится о загрузке и отображении изображений, поэтому у вас нет к.

Я написал класс, чтобы справиться с этим, поскольку это, похоже, повторяющаяся потребность в моих различных проектах:

UrlImageViewHelper заполнит ImageView с найденным изображением по URL.

образец сделает Изображение Google Поиск и загрузка/показать результаты асинхронно.

UrlImageViewHelper будет автоматически загрузите, сохраните и кэшируйте все URL-адреса изображения в BitmapDrawables. Дубликаты url не будут загружаться в память дважды. Битовая память управляется используя слабую справочную хэш-таблицу, так что как только изображение больше не будет используется вами, это будет мусор собранные автоматически.

в любом случае люди просят мой комментарий опубликовать его в качестве ответа. я отправляю.

Источник

Как загрузить ImageView по URL в Android?

Как вы используете изображение, на которое ссылается URL-адрес в ImageView ?

От разработчика Android :

Убедитесь, что в вашем AndroidManifest.xml установлены следующие разрешения для доступа в Интернет.

Сначала вам нужно загрузить изображение

Затем используйте Imageview.setImageBitmap для установки растрового изображения в ImageView

1. Picasso позволяет без проблем загружать изображения в ваше приложение – часто в одной строке кода!

Использовать Gradle:

Всего одна строка кода!

Многие распространенные ошибки загрузки изображений на Android автоматически обрабатываются Picasso

  • Обработка утилиты ImageView и отмена загрузки в адаптере.
  • Комплексные преобразования изображений с минимальным использованием памяти.
  • Автоматическое кэширование памяти и дисков.

2. Glide. Библиотека загрузки изображений и кеширования для Android ориентирована на плавную прокрутку

Читайте также:  Oziexplorer для андроид крякнутый 4pda

Использовать Gradle:

// Для простого представления:

// Для простого списка изображений:

Я написал класс, чтобы справиться с этим, поскольку это, кажется, повторяющаяся потребность в моих различных проектах:

UrlImageViewHelper заполнит ImageView с изображением, которое находится по URL-адресу.

Образец будет выполнять поиск изображений Google и загрузить / показать результаты асинхронно.

UrlImageViewHelper автоматически загружает, сохраняет и кэширует все изображения, обращаясь к BitmapDrawables. Дублирующие URL-адреса не будут загружаться в память дважды. Память растрового изображения управляется с использованием слабой справочной хеш-таблицы, поэтому, как только изображение больше не будет использоваться вами, это будет автоматически собираться мусором.

В любом случае люди просят мой комментарий, чтобы опубликовать его в качестве ответа. Я отправляю сообщения.

Принятый ответ выше, если вы загружаете изображение на основе нажатия кнопки, однако, если вы делаете это в новом действии, он замораживает пользовательский интерфейс на секунду или два. Оглядевшись, я обнаружил, что простая асинтеза устраняет эту проблему.

Чтобы использовать asynctask, добавьте этот класс в конце вашей деятельности:

И вызов из метода onCreate (), используя:

Результатом является быстро загружаемая активность и изображение, которое отображается через несколько секунд позже в зависимости от скорости сети пользователя.

Вы также можете использовать это изображение LoadImageView для загрузки изображения с URL-адреса:

После того, как вы добавили файл класса из этой ссылки, вы можете создать экземпляр изображения с URL-адресами:

И обновите его, используя:

Недавно я нашел здесь поток, так как мне нужно сделать аналогичную вещь для списка с изображениями, но принцип прост, так как вы можете прочитать в первом примере, показанном там (by jleedev). Вы получаете входной поток изображения (из Интернета)

Затем вы сохраняете изображение как Drawable, и вы можете передать его в ImageView (через setImageDrawable). Опять же из верхнего фрагмента кода взгляните на весь поток.

Привет, у меня самый простой код, попробуйте это

Здесь много хорошей информации … Недавно я нашел класс под названием SmartImageView, который пока работает очень хорошо. Очень легко включать и использовать.

ОБНОВЛЕНИЕ : я закончил тем, что написал сообщение в блоге об этом , поэтому ознакомьтесь с его помощью по использованию SmartImageView.

2ND UPDATE : теперь я всегда использую Picasso для этого (см. Выше) и очень рекомендую его. 🙂

Лучшей современной библиотекой для такой задачи, по моему мнению, является Пикассо на площади. Он позволяет загружать изображение в ImageView по URL-адресам с помощью одного слоя:

Это поможет вам …

Определите изображение и загрузите изображение в него …..

Затем Определите этот метод:

Простой и чистый способ сделать это – использовать библиотеку с открытым исходным кодом Prime .

Этот код проверен, он полностью работает.

Работа с графическим изображением в любом контейнере, например, в виде сетки в виде списка, обычная компоновка

Версия с обработкой исключений и задачей async:

Попробуйте этот путь, надеюсь, что это поможет вам решить вашу проблему.

Здесь я расскажу о том, как использовать внешнюю библиотеку «AndroidQuery» для загрузки изображения с url / server в режиме asyncTask, а также загружать кэшированное изображение в файл устройства или область кеша.

  • Загрузите библиотеку «AndroidQuery» здесь
  • Скопируйте / Вставьте эту банку в папку проекта lib и добавьте эту библиотеку в путь сборки проекта
  • Теперь я показываю демонстрацию того, как ее использовать.

activity_main.xml

MainActivity.java

Android Query может справиться с этим для вас и многое другое (например, прохождение кеша и загрузки).

Я думаю, что это лучший подход.

Это поздний ответ, как было предложено выше. AsyncTask будет и после того, как я AsyncTask немного, я нашел еще один способ для этой проблемы.

Я попробовал это сам, и у меня еще нет проблем.

Источник

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

Источник

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]

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?

Источник

Оцените статью