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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器