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格式解析

  • 2016-12-25 18:26
  • 67KB
  • 下载

retrofit2用simplexml解析xml

现在手上的项目后台返回的是XML字符串,用惯了JSON + GSON的我第一考虑的就是自动化解析,那么多接口,那么多属性,用DOM或者萨克斯解析太浪费时间了,而且扩展性也不好。网上的关于retrofi...

SAX类解析XML

  • 2016-06-17 12:03
  • 1.47MB
  • 下载

xstream解析xml

  • 2016-01-20 09:59
  • 497KB
  • 下载

Sax解析Xml文档

SAX(simpleAPIforXML)是一种XML解析的替代方法。相比于DOM,SAX是一种速度更快,更有效的方法。它逐行扫描文档,一边扫描一边解析。 在用Sax解析xml文档的时候不要忽略节点之...

解析xml工具类

  • 2016-09-27 15:22
  • 62KB
  • 下载

Markup115-XML解析类

  • 2015-03-26 15:43
  • 578KB
  • 下载

Java解析XML汇总(DOM/SAX/JDOM/DOM4j/XPath)

【目录】 一、【基础知识——扫盲】 二、【DOM、SAX、JDOM、DOM4j简单使用介绍】 三、【性能测试】 四、【对比】 五、【小插曲XPath】 六、【补充】 关键字:Java...

dom4j资源,xml解析和创建

  • 2015-04-21 16:10
  • 307KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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