2014-09-27 123 views
0

我想使用谷歌靜態地圖API,並下載我的位置的位圖圖像,並顯示在我的應用程序作爲圖像,我寫了這段代碼,但我的應用程序停止,是什麼問題?如何在Android中顯示來自Uri的位圖圖像?

代碼:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my); 

    String URL = "http://maps.google.com/maps/api/staticmap?center=48.858235,2.294571&zoom=15&size=200x200&sensor=false"; 
    Bitmap bmp = null; 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet request = new HttpGet(URL); 

    InputStream in = null; 
    try { 
     in = httpclient.execute(request).getEntity().getContent(); 
     bmp = BitmapFactory.decodeStream(in); 
     in.close(); 
    } catch (IllegalStateException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    ImageView vi=(ImageView)findViewById(R.id.salak); 
    vi.setImageBitmap(bmp); 


} 

我剛寫的這部分代碼在OnCreate()函數,並在.xml文件一個圖像瀏覽器來顯示圖像,但我的程序沒有Corectly工作,怎麼能我解決了這個問題?

+1

你應該發佈你的錯誤日誌,在我看來,你可能會從主線程異常的網絡崩潰,你應該看看異步任務做後臺線程的網絡 – JRowan 2014-09-27 19:39:54

回答

0

正如JRowan在他的評論中所說的,問題最可能的原因是您嘗試在主線程上進行網絡調用,這是不允許的。

看到這個: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

加載從URI的ImageView的,可以在這裏找到最簡單的方法是使用Square的畢加索庫:你把它下載並安裝

http://square.github.io/picasso/

一,那麼你可以加載你的ImageView像這樣:

Picasso.with(context).load(yourUrl).into(yourImageView); 

如果在一個活動中運行,您可以使用this作爲上下文。

相關問題