EastWR 2014-02-14 10:56 采纳率: 0%
浏览 1872

android 写网络图片查看器,代码看不出错,但就是结果不对,新手求帮助,帮忙挑挑错。

我反复检查了好几遍,感觉写的都正确。就是运行时没结果。
我打算访问的图片是自己创建的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();
 }
  • 写回答

2条回答 默认 最新

  • 搞什么灯儿 2014-02-18 13:37
    关注

    android4.0以后访问网络操作不能在主线程中 需要另外建立一个线程访问网络数据,目的是为了防止ANR,阻塞UI线程

    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵