i want to load multiple images by passing a url. unlike this tutorial http://www.learn2crack.com/2014/06/android-load-image-from-internet.html in which only one image is downloaded and is viewed using img.setImageBitmap(image); My question is how can i do to send url to a method to load an image for that url and the method return an image and then i show it in an imageview. then i pass some other url to it and get image in response and i show it in some other imageview.
-
Do you really want to do it in sequence, not in parallel? You could have one AsyncTask taking an array of URL:s and fetching all images in one task. Or you could start multiple AsyncTasks, each fetching one image. Your question is pretty vague since it seems you're asking about how to perform basic flow control (for loop etc). What did you try so far? – JHH Apr 07 '15 at 08:23
-
@JHH i want to do in in sequence – Beginner Apr 07 '15 at 08:26
-
@JHH i asked this question http://stackoverflow.com/questions/29469428/image-does-not-loaded-and-throwingjava-net-malformedurlexception but since it repeats the number of AsyncTask to be written to download every image but i need only one task to do downlod multiple images – Beginner Apr 07 '15 at 08:28
-
@JHH if this can be done by making an array of url then how each image can be set to imagview to be shown – Beginner Apr 07 '15 at 08:33
-
What would you need a library for to do such a simple task? – JHH Apr 07 '15 at 08:39
3 Answers
Ok assuming then you for some reason want to fetch the images one by one and in sequence, as opposed to in parallel, and assuming you have your URLs in a list, array etc, modify the tutorial example so that onPostExecute calls a method in your activity, either defined in a callback interface or on your class itself, and for each iteration pick one element from the list and start a new LoadImage job whenever the previous one is complete.
Example (untested) code:
public class MainActivity extends Activity {
Button load_img;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
private List<String> mURLs = new LinkedList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
load_img = (Button)findViewById(R.id.load);
img = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mURLs.add("http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png");
mURLs.add("some-other-URL");
loadNext();
}
});
private void loadNext() {
String url = mURLs.remove();
if (url != null) {
new LoadImage().execute(url);
}
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
loadNext();
}
}
}
In this example I set the image onto the same ImageView repeatedly which obviously makes no sense. You obviously have to keep track of which image goes onto which imageview by either sending the imageview as an argument to the task, or keep the imageviews (or their R.id.xxx ID's and call findById accordingly) in an array as well, or keep a counter, or.... There are a million ways to solve this.
Another approach is to send the array to the AsyncTask and have doInBackground simply loop over the array with a for-loop or similar.
Note however that a better approach might be to actually parallelize the tasks so that you make sure to utilize your available network bandwidth fully to fetch the images in parallel.

- 8,567
- 8
- 47
- 91
-
Actually i was facing these two problems that 1) i was not able to send view to the asyntask and 2) to set the loaded images into different imageviews. so please can you solve this – Beginner Apr 07 '15 at 09:14
-
Instead of setting the image on the imageview inside onPostExecute, call a method in the enclosing activity, like in my example, but let that method be the one responsible for assigning images to imageviews. Pass "image" along as a parameter to loadNext() for example. Then the AsyncTask doesn't need to know about the imageviews at all and you can keep that logic outside of it. – JHH Apr 07 '15 at 11:29
You can use android Volley Library for downloading the images.
Add volley.jar library in to your project
Image Request using Volley https://developer.android.com/training/volley/request.html#request-image
If you want to show images in a gridView / ListView.
Use
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="150dp"
android:layout_height="170dp"
android:layout_centerHorizontal="true" />
in your grid_item.xml or list_item.xml
In getView of your ListAdapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
// Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();
// Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);
}
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
private void GetMultipleImages() {
HttpGet httpGet = null;
try {
httpGet = new HttpGet(new URI("URL"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
RestTask task = new RestTask(getActivity(), ACTION_FOR_INTENT_CALLBACK);
task.execute(httpGet);
}
private class RestTask extends AsyncTask<HttpUriRequest, Void, String>
{
private static final String TAG = "AARestTask";
public static final String HTTP_RESPONSE = "httpResponse";
private Context mContext;
Activity context;
private HttpClient mClient;
private String mAction;
public RestTask(Context context, String action)
{
mContext = context;
mAction = action;
mClient = new DefaultHttpClient();
}
public RestTask(FragmentActivity activity, String action, HttpClient client)
{
mContext = context;
mAction = action;
mClient = client;
}
@Override
protected String doInBackground(HttpUriRequest... params)
{
try
{
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
return handler.handleResponse(serverResponse);
}
catch (Exception e)
{
// TODO handle this properly
e.printStackTrace();
return "";
}
}
@Override
protected void onPostExecute(String result)
{
Log.e(TAG, "RESULT = " + result);
/*Intent intent = new Intent(mAction);
intent.putExtra(HTTP_RESPONSE, result);
mContext.sendBroadcast(intent);*/
JSONObject jObject;
try {
jObject = new JSONObject(result);
JSONArray jSearchData = jObject.getJSONArray("data");
for (int i = 0; i < jSearchData.length(); i++) {
JSONObject objJson = jSearchData.getJSONObject(i);
String data = objJson.getString("id");
String imagesData = objJson.getString("images");
JSONArray jsonImages = new JSONArray("[" + imagesData + "]");
JSONObject imageObject = jsonImages.getJSONObject(0);
String images = imageObject.getString("thumbnail");
JSONArray imageArray = new JSONArray("[" + images + "]");
JSONObject urlObject = imageArray.getJSONObject(0);
String url = urlObject.getString("url");
urlArrayList.add(url);
}
imageAdapter = new InstaImageAdapter(getActivity(),urlArrayList);
Log.e("imageAdapter ==>",""+imageAdapter);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),4);
rvInstagramImage = (RecyclerView)getActivity().findViewById(R.id.rv_insta_img);
rvInstagramImage.setLayoutManager(layoutManager);
rvInstagramImage.setItemAnimator(new DefaultItemAnimator());
rvInstagramImage.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.item_offset));
rvInstagramImage.setAdapter(imageAdapter);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}

- 1
- 3