How to display images in ImageView from json data in android

I get json data. In this json, I have a URL for the image. Now I want to display this image in ImageView. How can i do this? Here is my code

class LoadInbox extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Home.this); pDialog.setMessage("Loading Inbox ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting Inbox JSON * */ protected String doInBackground(String... arg0) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = userFunctions.homeData(); Log.e("Data", json.toString()); // Check your log cat for JSON reponse Log.d("Inbox JSON: ", json.toString()); try { data = json.getJSONArray(TAG_DATA); Log.d("inbox array: ", data.toString()); // looping through All messages for (int i = 0; i < data.length(); i++) { JSONObject c = data.getJSONObject(i); // Storing each json item in variable String profile_img = c.getString(TAG_PROFILE_IMG); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_PROFILE_IMG, profile_img); // adding HashList to ArrayList inboxList.add(map); } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( Home.this, inboxList, R.layout.home_list_item, new String[] { TAG_PROFILE_IMG }, new int[] { R.id.profile_img2 }); // updating listview setListAdapter(adapter); } }); } 

here is my layout

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:id="@+id/profile_img2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="8dip" android:paddingLeft="8dip" android:paddingBottom="4dip" /> </RelativeLayout> 
+4
source share
3 answers

So, you want to create another AsyncTask that sets the URL, downloads the image and populates some control. Usually I do something like this:

 ImageView imageView = (ImageView)findById(R.id.blah); new ImageLoader( person.getImageUri(), imageView, 128, 128 ).execute(); 

ImageLoader will be another AsyncTask as follows:

 public class ImageLoader extends AsyncTask<URI,Integer,BitmapDrawable> { private Uri imageUri; private ImageView imageView; private int preferredWidth = 80; private int preferredHeight = 80; public ImageLoader( URI uri, ImageView imageView, int scaleWidth, int scaleHeight ) { this.imageUri = uri; this.imageView = imageView; this.preferredWidth = scaleWidth; this.preferredHeight = scaleHeight; } public BitmapDrawable doInBackground(URI... params) { if( imageUri == null ) return null; String url = imageUri.toString(); if( url.length() == 0 ) return null; HttpGet httpGet = new HttpGet(url); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute( httpGet ); InputStream is = new BufferedInputStream( response.getEntity().getContent() ); try { Bitmap bitmap = BitmapFactory.decodeStream(is); if( preferredWidth > 0 && preferredHeight > 0 && bitmap.getWidth() > preferredWidth && bitmap.getHeight() > preferredHeight ) { return Bitmap.createScaledBitmap(bitmap, preferredWidth, preferredHeight, false); } else { return bitmap; } } finally { is.close(); } } } public void onPostExecute( BitmapDrawable drawable ) { imageView.setImageBitmap( drawable ); } } 

You can then disable this AsyncTask when the image is anchored in your ListView by creating your own ListAdapter subclass. So you have to go down with the SimpleAdapter, because it's not so simple. This has many advantages, so you only upload displayed images. This means that a very small amount is loaded from the total. Also, your user can see the data before downloading the image in order to quickly access the data. If you did this in your existing AsyncTask, you uploaded each image, and the user would have to wait for each of them to complete before the data was shown to the user. There is something that can be improved. One AsyncTask uses its own thread, so you will be launching many threads potentially (10 or more) at the same time. This can kill your server with many clients. You can centralize them using an ExecutorService (i.e. a thread pool), but you have to mess up with AsyncTask and implement your own tool to start a task from the user interface thread and publish the results to the user interface thread. Secondly, your images will be loaded every time the user scrolls. To do this, I implemented my own caching scheme based on the image URI, so I load one image only once and return it from the cache. This is too much code to post here, but it is an exercise for the reader.

Also note that I am not sending back to the UI thread in onPostExecute (). This is because AsyncTask does this for me, I do not need to do it again, as your code above shows. You should simply remove this extra runnable and embed the code in onPostExecute ().

+4
source

you can try picasso is really easy to use and works very well.

 Picasso.with(this.getActivity()).load(person.getImageUri()).into(imageView); // if person.getImageUri() has the url image loaded from json 

What is it.

+1
source

What it looks like, you get more than one url (like in an array)

 1- Keep all the url in an hastable with key as url and value as image View. 2- Show your UI and with loading image. 3- create the other task download image one by one and update in the image view. 

as an example of a lazy image downloader ...

http://iamvijayakumar.blogspot.in/2011/06/android-lazy-image-loader-example.html

http://codehenge.net/blog/2011/06/android-development-tutorial-asynchronous-lazy-loading-and-caching-of-listview-images/

Android offline memory error with lazy loading images

Android lazy class of downloadable images consumes all my memory

Lazy Uploading images to Listview on Android (entry level)?

Lazy loading images in a ListView

0
source

Source: https://habr.com/ru/post/1416001/


All Articles