Android常用工具方法
2016-03-18 15:01
531 查看
/* 1. * 从流中解析新闻集合 * 使用pull解析器解析xml数据 */ private static List<NewInfo> getNewListFromInputStream(InputStream is) throws Exception { XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, "utf-8"); int eventType = parser.getEventType(); List<NewInfo> newInfoList = null; NewInfo newInfo = null; while(eventType != XmlPullParser.END_DOCUMENT ){ String tagNme = parser.getName();//节点名称 switch (eventType) { case XmlPullParser.START_TAG://<news> if("news".endsWith(tagNme)){ newInfoList = new ArrayList<NewInfo>(); }else if ("new".equals(tagNme)){ newInfo = new NewInfo(); }else if ("title".equals(tagNme)) { newInfo.setTitle(parser.nextText()); }else if ("detail".equals(tagNme)) { newInfo.setDetail(parser.nextText()); }else if ("comment".equals(tagNme)) { newInfo.setComment(Integer.valueOf(parser.nextText())); }else if ("image".equals(tagNme)) { newInfo.setImageUrl(parser.nextText()); } break; case XmlPullParser.END_TAG: if("new".equals(tagNme)){ newInfoList.add(newInfo); } break; default: break; } eventType = parser.next(); } return newInfoList; } 2.从输入流中读取数据(可转换为字符串) // 将流转换成字符串 private static String getStringInputStream(InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } /*is.close(); return bos.toByteArray(); //从流中读出数据返回出去 */ is.close(); // String html = bos.toString();//把流中数据转换成字符串 采用的是UTF-8 String html = new String(bos.toByteArray(), "GBK");// 在客户端更改,接收GBK编码格式,转换成字符串 bos.close(); return html; } (读一串字符串,一串!用字符流比较方便。。字节流向字符流的转换。 FileInputStream fis = new FileInputStream(path)1.先定义一个字符流对象。 BufferedReader reader = new BufferedReader();()里面接收的是一个reader的对象,就是那个转换流 BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); 3.//根据路径得到image图片(Bitmap) 加载网络图片 public static Bitmap getImage(String path){ HttpURLConnection conn = null; Bitmap bitmap = null; try { URL url = new URL(path); HttpURLConnection httpconn = (HttpURLConnection) url.openConnection(); httpconn.connect(); InputStream is = httpconn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); httpconn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return bitmap; }
相关文章推荐
- android studio 代码提交及冲突解决
- Modbus工业协议在Android中的应用
- Android --- 读取系统资源函数getResources()小结
- android数据存储的五种方式
- Android-zhi事件工具类(几天,几小时,几分钟前)
- Android屏幕适配全攻略(最权威的官方适配指导)
- 记录一点AndroidStudio使用SVN的经验
- Android加载长图那些事
- android Bitmap的内存管理
- android图片压缩
- RN控件之ProgressBarAndroid进度条
- Android 内存管理 &Memory Leak & OOM 分析
- (初级)单兵开发者开发环境最佳实践(Android+JavaWeb)
- Android 颜色渲染(十) ComposeShader组合渲染
- Android 颜色渲染(九) PorterDuff及Xfermode详解
- Android 颜色渲染(八) SweepGradient扫描/梯度渲染
- Android 中 Bitmap 和 Drawable 相互转换的方法
- Android 颜色渲染(七) RadialGradient 环形渲染实现水波纹效果
- Android 热补丁动态修复框架小结
- Android 颜色渲染(六) RadialGradient 环形渲染