【第22期】观点:IT 行业加班,到底有没有价值?

Xml解析

原创 2016年06月01日 09:32:33

这是Xml


MainActivity.java

package com.example.xmljiexi;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.example.adapter.MyAdapter;
import com.example.view.XListView;
import com.example.view.XListView.IXListViewListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class MainActivity extends Activity implements IXListViewListener {
	public int index = 1;
	private String url = "http://www.oschina.net/action/api/tweet_list?pageIndex="
			+ index;
	private XListView xlv;
	private List<Bean> list;
	private ArrayList<Bean> newlist = new ArrayList<Bean>();
	private HttpUtils httpUtils;
	private Bean bean;
	private MyAdapter adapter;
	private String Tag = "刷新";
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		xlv = (XListView) findViewById(R.id.xlv);
		xlv.setPullLoadEnable(true);
		xlv.setXListViewListener(this);
		httpUtils = new HttpUtils();
		handler = new Handler();
		// 请求数据
		inData(Tag);
		xlv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(MainActivity.this, SActivity.class);
				intent.putExtra("id", list.get(position - 1).id);
				startActivity(intent);
				finish();
			}
		});
	}

	private void setAdapter() {
		if (adapter == null) {
			adapter = new MyAdapter(this, newlist);
			xlv.setAdapter(adapter);
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	private void inData(final String str) {
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {

			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String xml = arg0.result;
				ByteArrayInputStream mInputStream = new ByteArrayInputStream(
						xml.getBytes());
				try {
					XmlPullParser parser = Xml.newPullParser();

					parser.setInput(mInputStream, "utf-8");

					int event = parser.getEventType();

					Bean mxml = null;

					while (event != XmlPullParser.END_DOCUMENT) {
						String name = parser.getName();
						switch (event) {
						case XmlPullParser.START_DOCUMENT:
							list = new ArrayList<Bean>();
							break;
						case XmlPullParser.START_TAG:
							if ("tweet".equals(name)) {
								mxml = new Bean();
							} else if ("id".equals(name)) {
								mxml.setId(Integer.parseInt(parser.nextText()));
							} else if ("portrait".equals(name)) {
								mxml.setPortrait(parser.nextText());
							} else if ("author".equals(name)) {
								mxml.setAuthor(parser.nextText());
							} else if ("body".equals(name)) {
								mxml.setBody(parser.nextText());
							} else if ("pubDate".equals(name)) {
								mxml.setPubDate(parser.nextText());
							} else if ("imgSmall".equals(name)) {
								mxml.setImgSmall(parser.nextText());
							} else if ("imgBig".equals(name)) {
								mxml.setImgBig(parser.nextText());
							}
							break;
						case XmlPullParser.END_TAG:
							if ("tweet".equals(name)) {
								list.add(mxml);
								mxml = null;
							}
							break;
						case XmlPullParser.END_DOCUMENT:
							break;
						}
						event = parser.next();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (str.equals("刷新")) {
					newlist.addAll(0, list);
				} else {
					newlist.addAll(list);
				}
				setAdapter();
			}
		});

	}

	private void onLoad() {
		xlv.stopRefresh();
		xlv.stopLoadMore();
		xlv.setRefreshTime("刚刚");
	}

	@Override
	public void onRefresh() {
	handler.postDelayed(new Runnable() {
		
		@Override
		public void run() {
			index=index+1;
			Tag="刷新";
			inData(Tag);
			onLoad();
		}
	}, 2000);
	}

	@Override
	public void onLoadMore() {
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				index=index+1;
				Tag="加载";
				inData(Tag);
				onLoad();
			}
		}, 2000);
	}

}

Bean.java

package com.example.xmljiexi;

public class Bean {
	public int id;
	public String portrait;
	public String author;
	public String body;
	public String pubDate;
	public String imgSmall;
	public String imgBig;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPortrait() {
		return portrait;
	}
	public void setPortrait(String portrait) {
		this.portrait = portrait;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
	public String getPubDate() {
		return pubDate;
	}
	public void setPubDate(String pubDate) {
		this.pubDate = pubDate;
	}
	public String getImgSmall() {
		return imgSmall;
	}
	public void setImgSmall(String imgSmall) {
		this.imgSmall = imgSmall;
	}
	public String getImgBig() {
		return imgBig;
	}
	public void setImgBig(String imgBig) {
		this.imgBig = imgBig;
	}
	@Override
	public String toString() {
		return "Bean [id=" + id + ", portrait=" + portrait + ", author="
				+ author + ", body=" + body + ", pubDate=" + pubDate
				+ ", imgSmall=" + imgSmall + ", imgBig=" + imgBig + "]";
	}
	
	
}

MyAdapter.java

package com.example.adapter;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.app.ImageLoaderUtils;
import com.example.view.RoundImageView;
import com.example.xmljiexi.Bean;
import com.example.xmljiexi.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MyAdapter extends BaseAdapter {

	private Context context;
	private List<Bean> list;
	private DisplayImageOptions options;

	public MyAdapter(Context context, List<Bean> list) {
		this.context = context;
		this.list = list;
		options = ImageLoaderUtils.initOptions();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = View.inflate(context, R.layout.item, null);
		RoundImageView portrait = (RoundImageView) view.findViewById(R.id.portrait);
		TextView author = (TextView) view.findViewById(R.id.author);
		TextView body = (TextView) view.findViewById(R.id.body);
		ImageView img = (ImageView) view.findViewById(R.id.img);
//		bitmapUtils.display(portrait, list.get(position).portrait);
		ImageLoader.getInstance().displayImage(list.get(position).portrait, portrait, options);
		author.setText(list.get(position).author);
		body.setText(list.get(position).body);
//		bitmapUtils.display(img, list.get(position).imgSmall);
		ImageLoader.getInstance().displayImage(list.get(position).portrait, img, options);
		return view;
	}

}

<strong>ImageLoaderUtils.java
缓存
</strong>

package com.example.app;

import com.example.xmljiexi.R;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.content.Context;
import android.graphics.Bitmap;

public class ImageLoaderUtils {
	 public static void initConfiguration(Context context) {
		 Builder configuration = new ImageLoaderConfiguration.Builder(context);
		 configuration.memoryCacheExtraOptions(480, 800)
			  .diskCacheExtraOptions(480, 800, null)
			  // .taskExecutor(null)
			  // .taskExecutorForCachedImages()
			  .threadPoolSize(3)
			  // default 线程优先级
			  .threadPriority(Thread.NORM_PRIORITY - 2)
			  // default
			  .tasksProcessingOrder(QueueProcessingType.FIFO)
			  // // default设置在内存中缓存图像的多种尺寸
			  // 加载同一URL图片时,imageView从小变大时,从内存缓存中加载
			  .denyCacheImageMultipleSizesInMemory()
			  // 超过设定的缓存大小时,内存缓存的清除机制
			  .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
			  // 内存的一个大小
			  .memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(13)
			  // default 将图片信息缓存到该路径下
			  // default 磁盘缓存的大小
			  .diskCacheSize(50 * 1024 * 1024)
			  // 磁盘缓存文件的个数
			  .diskCacheFileCount(100)
			  // 磁盘缓存的文件名的命名方式//一般使用默认值 (获取文件名称的hashcode然后转换成字符串)或MD5 new
			  // Md5FileNameGenerator()源文件的名称同过md5加密后保存
			  .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
			  // 设置默认的图片加载
			  // 使用默认的图片解析器
			  .imageDecoder(new BaseImageDecoder(true)) // default
			  .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
			  .writeDebugLogs();
		 ImageLoader.getInstance().init(configuration.build());
	 }
	 public static DisplayImageOptions initOptions() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.ic_launcher)
            .showImageOnFail(R.drawable.ic_launcher)
            .cacheInMemory(true)
            .cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565)
             // 是否考虑JPEG图像EXIF参数(旋转,翻转)
            .considerExifParams(true)
            // 设置图片以如何的编码方式显示
            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
            // 设置图片的解码类型//
            .bitmapConfig(Bitmap.Config.RGB_565)
            // 设置图片在下载前是否重置,复位
            .resetViewBeforeLoading(true)
            // 是否设置为圆角,弧度为多少
            .displayer(new RoundedBitmapDisplayer(20))
            // 是否图片加载好后渐入的动画时间
            .displayer(new FadeInBitmapDisplayer(100))
            // 构建完成 
            .build();
        return options;
    
    }
}

MyApplication.java 



package com.example.app;

import android.app.Application;

public class MyApplication extends Application {
	@Override
	public void onCreate() {
		super.onCreate();
		ImageLoaderUtils.initConfiguration(getApplicationContext());
	}

}

SActivity.java

package com.example.xmljiexi;

import java.io.ByteArrayInputStream;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Xml;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.app.ImageLoaderUtils;
import com.example.view.RoundImageView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class SActivity extends Activity {
	private int index;
	private RoundImageView portrait;
	private TextView author;
	private TextView pubDate;
	private TextView body;
	private ImageView img;
	private BitmapUtils bitmapUtils;
	private HttpUtils httpUtils;
	private String url="http://www.oschina.net/action/api/tweet_detail?id=";
	private Bean bean;
	private DisplayImageOptions options;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_s);
		Intent intent = getIntent();
		index = intent.getIntExtra("id", 0);
		options = ImageLoaderUtils.initOptions();
		portrait = (RoundImageView) findViewById(R.id.portrait);
		author = (TextView) findViewById(R.id.author);
		pubDate = (TextView) findViewById(R.id.pubDate);
		body = (TextView) findViewById(R.id.body);
		img = (ImageView) findViewById(R.id.img);
		bitmapUtils = new BitmapUtils(this);
		httpUtils = new HttpUtils();
		inData();
	}
	private void inData() {
		httpUtils.send(HttpMethod.GET, url+index, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Toast.makeText(SActivity.this, "网络请求失败", 0).show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String string=arg0.result;
				ByteArrayInputStream inputStream = new ByteArrayInputStream(string.getBytes());
				XmlPullParser parser = Xml.newPullParser();
				try {
					parser.setInput(inputStream, "utf-8");
					int type = parser.getEventType();
					while(type!=XmlPullParser.END_DOCUMENT){
						String name=parser.getName();
						switch (type) {
						case XmlPullParser.START_TAG:
							if("tweet".equals(name)){
								bean=new Bean();
							}else if("id".equals(name)){
								bean.id=Integer.parseInt(parser.nextText());
							}else if("portrait".equals(name)){
								bean.portrait=parser.nextText();
							}else if("author".equals(name)){
								bean.author=parser.nextText();
							}else if("body".equals(name)){
								bean.body=parser.nextText();
							}else if("pubDate".equals(name)){
								bean.pubDate=parser.nextText();
							}else if("imgBig".equals(name)){
								bean.imgBig=parser.nextText();
							}
							break;
						}
						type=parser.next();
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
//				bitmapUtils.display(portrait, bean.portrait);
				ImageLoader.getInstance().displayImage(bean.portrait, portrait, options);
				author.setText(bean.author);
				body.setText(bean.body);
				pubDate.setText(bean.pubDate);
//				bitmapUtils.display(img, bean.imgBig);
				ImageLoader.getInstance().displayImage(bean.imgBig, img, options);
			}

		});
		
	}



}





版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

XML解析

1. XML总结1.1. XML简介XML : 可扩展的标记语言。(和HTML非常类似的) - 可扩展的。 - 自定义的标签。与HTML区别: XML传输数据,HTML是显示数据。XML的版本: ...

Oracle中通过游标执行带参数的存储过程实现解析CLOB字段内的xml字符串:

摘要:近来之前的项目数据出现了问题,原因是由于之前在设计数据库的时候把时间字段设置成了字符串格式,所以给后期的数据操作带来了很大的麻烦,这里提醒一下各位程序猿,以后在开发项目的时候时间字段一定要是时间字段,不要为了方便操作就设成字符串,这样后期改你带来的麻烦是你想象不到的,接下来就看看我解决这个问题...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

android 微信支付返回XML格式数据的解析方法

此篇主要是为了那些做微信支付需要解析XML的朋友少写代码而创建,直接用即可: 一般我们在请求网络的时候,返回的都是Json格式的字符串,对此我们已经司空见惯,并且基本都知道如何去解析;但是有些情况下,...

[Java开发之路](11)SAX解析XML文档

1. 简介 <div style="font-family: 微软雅黑,'Microsoft YaHei',Georgia,Helvetica,Arial,sans-serif,

dom4j 解析xml文件(涉及知识点:dom4j,XPath,递归)

dom4j解析xml文件
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)