您的位置:首页 > 移动开发 > Android开发

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: