我反复检查了好几遍,感觉写的都正确。就是运行时没结果。
我打算访问的图片是自己创建的web工程上的图片,访问的地址也把localhost改为了相应的ip地址(ip是通过cmd->ipconfig查询得到)
我也添加了网络访问权限。
个人感觉不是布局导致的问题,因为程序运行后,那个吐司的报错一直都显示。如果是布局有问题,最多看不到图片。
感觉把该注意的问题都注意到了,但是还是运行有问题,希望各位大大们帮忙看一下,小弟初学。谢谢各位了。
MainActivity中的代码
public class MainActivity extends Activity {
private EditText imagePath;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePath = (EditText) this.findViewById(R.id.imagePath);
imageView = (ImageView) this.findViewById(R.id.imageView);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
private final class ButtonClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path = imagePath.getText().toString();
try {
byte[] data = ImageService.getImage(path);//此函数的代码见下面
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
}
}
}
Service层的关键代码:
public class ImageService {
public static byte[] getImage(String path) throws Exception{
// TODO Auto-generated method stub
URL url = new URL(path);
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();//基于http协议连接对象
conn.setConnectTimeout(5000);//5秒超时即自动关闭
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream inStream = conn.getInputStream();
return StreamTool.read(inStream);此函数代码见下面
}
return null;
}
}
StreamTool工具函数的代码:
public static byte[] read(InputStream inStream) throws Exception{
// TODO Auto-generated method stub
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while(( len = inStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}