关闭

HttpUtils&Pull解析XML

100人阅读 评论(0) 收藏 举报

@Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 httpUtils = new HttpUtils();

        lv = (XListView) findViewById(R.id.lv);

        lv.setPullLoadEnable(true);

        lv.setXListViewListener(this);

        list = new ArrayList<Bean>();

        inData();

        lv.setOnItemClickListener(new OnItemClickListener() {





@Override

public void onItemClick(AdapterView<?> parent, View view,

int position, long id) {

Intent intent=new Intent(MainActivity.this,InfoActivity.class);

                intent.putExtra("id", list.get(position-1).id);

                startActivity(intent);

}

        });

private void setAdapter() {

if(adapter==null){

adapter=new MyAdapter(list,this);

lv.setAdapter(adapter);

}else{

adapter.notifyDataSetChanged();

}

}

private void inData() {

httpUtils.send(HttpMethod.GET, url+(index++), new RequestCallBack<String>() {

@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(MainActivity.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("imgSmall".equals(name)){
bean.imgSmall=parser.nextText();
}
break;
case XmlPullParser.END_TAG:
if("tweet".equals(name)){
list.add(bean);
bean=null;
}
break;
}
type=parser.next();
}

} catch (Exception e) {
e.printStackTrace();
}
setAdapter();
}

});

}

private void onLoad() {

        lv.stopRefresh();

        lv.stopLoadMore();

        lv.setRefreshTime("刚刚");

    }

@Override

public void onRefresh() {

list.clear();

        inData();

        onLoad();

}



@Override

public void onLoadMore() {

inData();

        onLoad();

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:653次
    • 积分:61
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章存档