Narendra
Narendra

Reputation: 1868

Fetch and display image on click of a button

I want to fetch an image on click of a button and display it in the same activity. This is what i have tried

public class MainActivity extends Activity {


    ImageView imView;
    String imageUrl="http://variable3.com/files/images/email-sig.jpg";
    Random r= new Random();
   /** Called when the activity is first created. */ 
   @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);
       setContentView(R.layout.main);

       Button bt3= (Button)findViewById(R.id.get_imagebt);
       bt3.setOnClickListener(getImgListener);

       imView = (ImageView)findViewById(R.id.imview);
       Log.i("img already downloaded","img");
   }    

   View.OnClickListener getImgListener = new View.OnClickListener()
   {

         public void onClick(View view) {
              // TODO Auto-generated method stub

              //i tried to randomize the file download, in my server i put 4 files with name like
                       //png0.png, png1.png, png2.png so different file is downloaded in button press
             int i =r.nextInt(4);
              downloadFile(imageUrl);
              Log.i("im url",imageUrl);
         }

   };


   Bitmap bmImg;
   void downloadFile(String fileUrl){
         URL myFileUrl =null;          
         try {
              myFileUrl= new URL(fileUrl);
         } catch (MalformedURLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         }
         try {
              HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
              conn.setDoInput(true);
              conn.connect();
              int length = conn.getContentLength();
              InputStream is = conn.getInputStream();

              Log.i("im connected","Download");
              bmImg = BitmapFactory.decodeStream(is);
              imView.setImageBitmap(bmImg);
         } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         }
    }

}

Upvotes: 2

Views: 1927

Answers (1)

Egor
Egor

Reputation: 40203

Didn't understand your question, but if it's about that comment about randomizing the download, then just add your i variable to the downloadFile() method parameters:

void downloadFile(String fileUrl, int i)

Then add a switch block to the method's body and make it download the file you need for a current value of i. Hope this is what you needed.

Upvotes: 1

Related Questions