I am tring to get the image width and height in android and load accordingly buy my below code is working fine in 2.3.3 but when i test in higher version(4.0) its height and width are giving null pointer exception…Below is my code…
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;
}
}
As of API 11, if you are executing this code on the UI thread, the network access will throw a
NetworkOnMainThreadException. You don’t post your logcat output (which would be very helpful), but I suspect this is what’s happening. As a result,LoadImageFromWebOperationswill returnnulland you will get a NPE when you try to access the drawable properties.You need to run this code in a worker thread. See the article Keeping Your App Responsive.