Murugan.P Murugan.P - 1 month ago 4
Android Question

Load multiple Url images without using third party libraries in Recyclerview

Hi all I'm new to Android, I'm facing difficulty in loading Multiple images through URL into a Recycler view, My task is not to use any third Party Libraries and also not to add in string array in xml file. Is it Possible to loop an URL? for example "http://onethousandpaintings.com/imgs/numbers/number_1.png", if the number is change the image correspondingly changes.try it yourself once! I'm thinking an way to increment that number in a "For Loop" but could not figure it out. Kindly provide me an solution for it.

Answer Source

@sample AsycTask Code, you can pass the url to this class by execute method.

public class ShowImage extends AsyncTask<String,Void,Bitmap>{
     private  WeakReference<ImageView> imageview;
     public ShowImage(ImageView imv){
        imageview=new WeakReference<ImageView>(imv);
     }
      /** Background process
               * input:url
               * output: Bitmap image
               * It passed into onPostExecute method
               **/
    @Override
    protected Bitmap doInBackground(String... urls) {

       return getBitMapFromUrl(urls[0]);

    }
    /** This method called after the doINputBackground method
     * input:Bitmap image
     * output: image set into the image view
     * Image view  passed from RecyclerViewOperation to ShowImage class through constructor
     **/
    @Override
    protected void onPostExecute(Bitmap result) {
        if((imageview!=null)&&(result!=null)){
            ImageView imgview=imageview.get();


             if(imgview!=null){

                 imgview.setImageBitmap(result);
             }
        }
    }
    /** This method called by doInBackground method
     * input:url
     * output: Bitmap image
     *
    **/
    private Bitmap getBitMapFromUrl( String imageuri){
        HttpURLConnection connection=null;

        try {
            URL url=new URL(imageuri);
          //  Log.d("bucky","bitmap" + imageuri);
            connection= (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream is=connection.getInputStream();
            Bitmap mybitmap=BitmapFactory.decodeStream(is);

            return mybitmap;


        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        finally {
            if(connection!=null) {
                connection.disconnect();
            }
        }
    }

}