tags:

views:

46

answers:

1

Hi All,

I am developing an app in android, which basically visits a given url and downloads an image.

Now i want to populate this downloaded image and show it in thumbnail view.

I have tried out displaying the same from SD Card, but when i am doing the same for downloaded files, it doesn't seems to work.

public View getView(int position,View convertView,ViewGroup parent)                
{  
  System.gc();  
  ImageView i = new ImageView(mContext.getApplicationContext());  
    if (convertView == null)    
    {  
          //imagecursor.moveToPosition(position);  
          //int id = imagecursor.getInt(image_column_index);  
          //i.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""+ id));  
          i.setImageBitmap(bitmap);  
          i.setScaleType(ImageView.ScaleType.FIT_CENTER);  
          i.setLayoutParams(new GridView.LayoutParams(100, 100));  
    }  
    else  
    {  
       i = (ImageView) convertView;
    }
    return i;  
}
+1  A: 

You can download the file and write it to the storage using URL, HttpConnection & Inputstream/Outputsteam. Once its downloaded you can display it in your ImageView.

I had done this using an AsyncTask:

@Override
        protected Void doInBackground(URL... urls) {
            for (int i = 0; i < urls.length; i++) {

                try {

                    Pattern pattern = Pattern.compile("([a-zA-Z]*.[jpeg|png])$");
                    Matcher matcher = pattern.matcher(urls[i].getFile());

                    if (matcher.find()) {

                        URLConnection connection = urls[i].openConnection();
                        int fileSize = connection.getContentLength();
                        mFileName = matcher.group();

                        String filePath = Environment
                                .getExternalStorageDirectory()
                                + File.separator + mFileName;

                        InputStream input = new BufferedInputStream(urls[i]
                                .openStream());

                        OutputStream output = new FileOutputStream(filePath);

                        byte data[] = new byte[1024];

                        long total = 0;
                        int count;

                        while ((count = input.read(data)) != -1) {
                            total += count;
                            int value = (int) (total * 100 / fileSize);
                            output.write(data, 0, count);
                            onProgressUpdate(value);
                        }

                        output.flush();
                        output.close();
                        input.close();

                        // Now display the image in your ImageView

                    }

                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            return null;
        }
Sameer Segal