2011-05-04 68 views
2

我想單擊按鈕獲取圖像並將其顯示在同一活動中。這就是我試圖單擊按鈕時獲取並顯示圖像

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(); 
     } 
    } 

} 
+0

你能描述你面臨什麼問題嗎? – chaitanya 2011-05-04 08:17:04

+0

編譯代碼後出現問題java.net.UnknowhostException:主機已解決 – Narendra 2011-05-04 09:54:51

+0

您是否已將android.permission.INTERNET添加到您的清單文件中? – chaitanya 2011-05-04 12:44:47

回答

1

沒明白你的問題,但如果它是關於關於隨機下載該註釋,然後只是你我變量添加到downloadFile()方法的參數:

void downloadFile(String fileUrl, int i) 

然後將一個開關塊添加到方法的主體,並使其下載當前值爲i所需的文件。希望這是你需要的。