2013-02-05 53 views
0

我打算在Android中獲取圖像的寬度和高度,並相應地加載購買我的下面的代碼在2.3.3工作正常,但是當我測試更高版本(4.0)其高度和寬度是給空指針異常......下面是我的代碼...可繪製的高度和寬度不工作在Android ICS

  Drawable drawable = null; 
      drawable = LoadImageFromWebOperations(logo_url.replace(" ", "%20")); 
      System.out.println("Width" + drawable.getMinimumWidth()); 
      System.out.println("Height" + drawable.getMinimumHeight()); 
      int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, drawable.getMinimumWidth(), mCtx.getResources().getDisplayMetrics()); 
      int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, drawable.getMinimumHeight(), mCtx.getResources().getDisplayMetrics()); 
      client_logo.setMinimumHeight(height); 
      client_logo.setMinimumWidth(width); 
      client_logo.setImageDrawable(drawable); 


      public Drawable LoadImageFromWebOperations(String url){ 
System.out.println(url); 

    try{ 
     InputStream is = (InputStream) new URL(url).getContent(); 
     Drawable d = Drawable.createFromStream(is, "src name"); 
     return (d); 
    }catch (Exception e) { 
     //System.out.println("Exc="+e); 
     return null; 
    } 
} 

回答

0

由於API 11,如果你是在UI線程上執行該代碼,網絡訪問將拋出一個NetworkOnMainThreadException。你不會發布你的logcat輸出(這將是非常有用的),但我懷疑這是發生了什麼。因此,LoadImageFromWebOperations將返回null,當您嘗試訪問可繪製屬性時,您將得到一個NPE。

您需要在工作線程中運行此代碼。請參閱文章Keeping Your App Responsive

+0

工作了很長時間...我的網絡操作加載到後臺本身.... – user1051599