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 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号