How to display an image from the internet in android?

前端 未结 4 1271
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 12:04

How can I display image in an ImageView in android from a URL (from the internet)?

4条回答
  •  感动是毒
    2020-12-09 12:43

    first u need to hit image url and store the server Data as byte array, then u need to convert these byte data into Bitmap image.. Here is the code

                    String myfeed="http://174.136.1.35/dev/atmsearch/visa.jpg";
    
                    try{
    
                        URL url=new URL(myfeed);
                        URLConnection connection=url.openConnection();
                        connection.setDoOutput(true);
                        connection.setDoOutput(true);
                        connection.setRequestProperty("METHOD", "POST");
                        connection.setRequestProperty("Content-Type","application/x-www-from-urlencoded");
    
                        HttpURLConnection httpConnection=(HttpURLConnection)connection;
    
                        int responsecode=httpConnection.getResponseCode();
    
                        if(responsecode==HttpURLConnection.HTTP_OK){
                            InputStream in=((URLConnection)httpConnection).getInputStream();
                            int len=0;
                            Bitmap b=BitmapFactory.decodeStream(in);
    
    
    
                            System.out.println(b.toString());
    
    
                            byte[] data1=new byte[1024];
    
                            while(-1!=(len=in.read(data1))){
                                System.out.println("--input stream--");
                                datafromserver.append(new String(data1,0,len));
    
                            }
                            //System.out.println(datafromserver);
                        }
    
                    }catch(IOException e){
                        System.out.println("Error...."+e);
                        //Toast.makeText(context, text, duration)
    
                    }
    

    // Now set the bitmap image in image view imageview.setImageBitmap(b);

提交回复
热议问题