// Activity
public class InfoActivity extends Activity {
String url="http://apis.juhe.cn/goodbook/catalog?key=9d6ef8c31647a206e05fcaff70527182&dtype=xml";Context context;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
context=this;
init();
}
private void init() {
listView = (ListView) findViewById(R.id.listView);
getBooksData();
}
private void getBooksData(){
HttpUtils utils = new HttpUtils();
utils.send(HttpMethod.GET, url, new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(context, "请求失败", 0).show();
System.out.println("请求失败");
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
String rs = arg0.result;
XStream xStream = new XStream();
xStream.processAnnotations(Books.class);
Books b=(Books) xStream.fromXML(rs);
List<Item> items = b.result.item;
Toast.makeText(context, items.toString(), 0).show();
MyBaseAdapter adapter = new MyBaseAdapter(context, items);
listView.setAdapter(adapter);
}
});
}
}
// main_activity
@XStreamAlias("root")
public class Books {
public String resultcode;
public String reason;
public Result result;
public String error_code;
@XStreamAlias("result")
public class Result{
@XStreamImplicit(itemFieldName="item")
public List<Item> item;
}
@XStreamAlias("item")
public class Item{
public String id;
public String catalog;
}
}
// adapter
public class MyBaseAdapter extends BaseAdapter{
Context context;
List<Item> list;
public MyBaseAdapter(Context context, List<Item> list) {
super();
this.context = context;
this.list = list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView = View.inflate(context, R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.text=(TextView) convertView.findViewById(R.id.text1);
convertView.setTag(viewHolder);
}else{
viewHolder=(ViewHolder) convertView.getTag();
}
Item item = list.get(position);
viewHolder.text.setText(item.catalog);
return convertView;
}
class ViewHolder{
TextView text;
}
}