使用下面这个获取数据的方法发生异常,怎么回事?请大家帮忙看看,连了网。public static InputStream getRequest(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); if (conn.getResponseCode() == 200){ return conn.getInputStream(); } return null; }
11-01 08:13:40.134: W/System.err(1066): java.lang.NullPointerException
怎么解决呢
例如
ImageView iv;
iv.setImageBitmap(bm);
这样就会报错
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.e("e","start");
String path="http://img.my.csdn.net/uploads/201210/29/1351519538_9960.png";
try {
InputStream is=ImageUtil.getRequest(path);
byte[] b=ImageUtil.readInputStream(is);
Bitmap bm=ImageUtil.byteToBitmap(b);
iv=(ImageView)findViewById(R.id.iv);
URL uri=new URL(path);
iv.setImageBitmap(bm);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("e","ec");
e.printStackTrace();
}
}
}
class ImageUtil { public static InputStream getRequest(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); if (conn.getResponseCode() == 200){ return conn.getInputStream(); }
Log.e("e","null");
return null; }
public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray();}
public static Bitmap byteToBitmap(byte[] byteArray){ if(byteArray.length!=0){ return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); } else { return null; } }
}
这个权限加上了吗