AndroidDev
AndroidDev

Reputation: 21237

Display Image from URL on Custom Spinner

I've built a custom spinner that includes an ImageView on each row. It all works perfectly when I load the image directly from an existing drawable stored locally. But my objective is to get these images from a URL, ideally lazily, because the image could be unique to any row. Here's what I've got at the moment:

 public View getCustomView(int position, View convertView, ViewGroup parent) {

     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     View row = inflater.inflate(R.layout.row, parent, false);

     ImageView this_picture = (ImageView)row.findViewById(R.id.image);
     Drawable d = LoadImageFromWebOperations("fake_person");

     if (d == null) {
         System.err.println("no image");
     } else{
         this_picture.setImageDrawable(d);
     }

     TextView label = (TextView) row.findViewById(R.id.name);
     label.setText(my_list.get(position));

     return row;
 }

 public static Drawable LoadImageFromWebOperations(String this_name) {

     try {
         InputStream is = (InputStream) new URL("https://www.mobilenicity.com/silhouette_male.png").getContent();
         Drawable d = Drawable.createFromStream(is, "src name"); 
         return d;
     } catch (Exception e) {
         return null;
     }
}

This will always return a null value for the image (with the log output no image). I'm pretty sure that this is because the url call hasn't returned in time, but I don't know what to do to resolve this. Any advice is appreciated. Thanks!

Upvotes: 0

Views: 583

Answers (1)

user957654
user957654

Reputation:

you should use AsyncTask like the following :

public class LoadImage extends AsyncTask <Void , Void , Drawable > {

private String imageUrl ; 
private ImageView imageView ; 

public LoadImage(String url , ImageView imageView ){
this.imageUrl = url ;
this.imageView = imageView ;
}

 protected Drawable doInBackground(Void... params) {    

try {
         InputStream is = (InputStream) new URL(this.imageUrl).getContent();
         Drawable d = Drawable.createFromStream(is, "src name"); 
         return d;
     } catch (Exception e) {
         return null;
     }

}  



       protected void onPostExecute(Drawable result) {      
    imageView.setImageDrawable(result); 
    } 

}

and call it from you getView method in your adapter like the following :

new LoadImage(url , imageView).execute();

Hope that helps .

Upvotes: 1

Related Questions