通过Xutils网络请求数据,展示QQ信息在listView上,在这里会有XlistView xml pull等不少的功能来实现这个demo,图片使用ImageloderUtils处理机制
下面我们来直接看代码吧:
1.MainActivity.class
<span style="font-size:18px;">import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import com.example.month1_adapter.MyBaseAdapter;
import com.example.month1_bean.News;
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 me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity implements IXListViewListener {
String path = "http://www.oschina.net/action/api/tweet_list";
boolean isRefresh = false;
ArrayList<News> myList = new ArrayList<News>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xlistview = (XListView) findViewById(R.id.xlistview);
xlistview.setPullLoadEnable(true);
xlistview.setXListViewListener(this);
xlistview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("id", myList.get(position-1).getId());
startActivity(intent);
}
});
getpath();
}
int index = 0;
private News news;
private MyBaseAdapter myBaseAdapter;
private XListView xlistview;
public void getpath() {
HttpUtils httpUtils = new HttpUtils();
String mypath = path + "?uid=0&pageIndex=" + index + "&pageSize=20";
httpUtils.send(HttpMethod.GET, mypath, new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
// TODO Auto-generated method stub
System.out.println("----------------"+arg1);
}
@Override
public void onSuccess(ResponseInfo<String> info) {
String result = info.result;
ByteArrayInputStream array = new ByteArrayInputStream(result
.getBytes());
System.out.println(result);
ArrayList<News> listnews=listnews(array);
if (isRefresh) {
myList.clear();
}
myList.addAll(listnews);
if (myBaseAdapter == null) {
myBaseAdapter = new MyBaseAdapter(MainActivity.this, myList);
xlistview.setAdapter(myBaseAdapter);
} else {
myBaseAdapter.notifyDataSetChanged();
}
// 消失进度
onLoad();
}
});
}
private ArrayList<News> listnews(InputStream inputStream) {
ArrayList<News> list=new ArrayList<News>();
XmlPullParser newPullParser=Xml.newPullParser();
try {
newPullParser.setInput(inputStream,"utf-8");
int eventype=newPullParser.getEventType();
while(eventype!=XmlPullParser.END_DOCUMENT){
String name=newPullParser.getName();
switch (eventype) {
case XmlPullParser.START_TAG:
if ("tweet".equals(name)) {
news = new News();
} else if ("id".equals(name)) {
news.setId(Integer.parseInt(newPullParser.nextText()));
} else if ("portrait".equals(name)) {
news.setPortrait(newPullParser.nextText());
} else if ("body".equals(name)) {
news.setBody(newPullParser.nextText());
} else if ("author".equals(name)) {
news.setAuthor(newPullParser.nextText());
} else if ("imgSmall".equals(name)) {
news.setImgSmall(newPullParser.nextText());
} else if ("imgBig".equals(name)) {
news.setImgBig(newPullParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("tweet".equals(name)) {
list.add(news);
news = null;
}
break;
default:
break;
}
eventype = newPullParser.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public void onRefresh() {
index=0;
isRefresh=true;
getpath();
}
@Override
public void onLoadMore() {
// TODO Auto-generated method stub
index++;
getpath();
}
private void onLoad() {
xlistview.stopRefresh();
xlistview.stopLoadMore();
xlistview.setRefreshTime("刚刚");
}
}
</span>
2.MyBaseAdapter适配器
<span style="font-size:18px;">import java.util.ArrayList;
import com.example.month1.ImageloderUtils;
import com.example.month1.R;
import com.example.month1_bean.News;
import com.lidroid.xutils.BitmapUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
@SuppressLint("ViewHolder")
public class MyBaseAdapter extends BaseAdapter {
private Context context;
private ArrayList<News> mylist;
private DisplayImageOptions setImgOptions;
public MyBaseAdapter(Context context,ArrayList<News> mylist) {
this.context=context;
this.mylist=mylist;
setImgOptions = ImageloderUtils.setImgOptions();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mylist.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) {
View view = View.inflate(context, R.layout.list_view, null);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
TextView tv_des = (TextView) view.findViewById(R.id.tv_des);
ImageView iv_icon = (ImageView) view.findViewById(R.id.iv);
ImageView iv_info = (ImageView) view.findViewById(R.id.info);
tv_des.setText(mylist.get(position).getBody());
tv_title.setText(mylist.get(position).getAuthor());
ImageLoader.getInstance().displayImage(
mylist.get(position).getImgSmall(), iv_icon, setImgOptions);
ImageLoader.getInstance().displayImage(mylist.get(position).getImgBig(),
iv_info, setImgOptions);
return view;
}
}
</span>
3.News实体类
<span style="font-size:18px;">public class News {
private int id;
private String portrait;
private String imgSmall;
private String imgBig;
private String body;
private String author;
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 getImgSmall() {
return imgSmall;
}
public void setImgSmall(String imgSmall) {
this.imgSmall = imgSmall;
}
public String getImgBig() {
return imgBig;
}
public void setImgBig(String imgBig) {
this.imgBig = imgBig;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public News(int id, String portrait, String imgSmall, String imgBig,
String body, String author) {
super();
this.id = id;
this.portrait = portrait;
this.imgSmall = imgSmall;
this.imgBig = imgBig;
this.body = body;
this.author = author;
}
public News() {
super();
}
}
</span>
<span style="font-size:18px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<me.maxwin.view.XListView
android:id="@+id/xlistview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout></span>
5.list_view.xml
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/ll" />
</LinearLayout>
</span>
6.ImageloderUtils
<span style="font-size:18px;">import java.io.File;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
public class ImageloderUtils {
/**
* 初始化ImageLoader
*
* @param context
*/
public static void initImgLoader(Context context) {
// 缓存路径
String cachePath = Environment.getExternalStorageDirectory()
+ "/Android/data/" + context.getPackageName() + "/cache/";
// 获取到缓存的目录地址
File cacheDir = StorageUtils.getOwnCacheDirectory(context, cachePath);
Log.d("cacheDir", cacheDir.getPath());
/* ImageLoader配置 */
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
context)
// .memoryCacheExtraOptions(480, 800)//每个缓存文件的最大宽高
.threadPoolSize(3)
// 线程池内加载线程的数量
.threadPriority(Thread.NORM_PRIORITY - 2)
// 线程优先级
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new WeakMemoryCache())
// .memoryCache(new UsingFreqLimitedMemoryCache(2*1024*1024))
.memoryCacheSize(2 * 1024 * 1024)
.diskCacheSize(50 * 1024 * 1024)
// .discCacheFileNameGenerator(new
// Md5FileNameGenerator())//MD5加密uri名称
// .discCacheFileNameGenerator(new
// HashCodeFileNameGenerator())//hashcode加密uri名称
.tasksProcessingOrder(QueueProcessingType.FIFO)
.diskCache(new UnlimitedDiskCache(cacheDir))
// 自定义缓存路径
.imageDownloader(
new BaseImageDownloader(context, 5 * 1000, 30 * 1000))
.writeDebugLogs().build();
// 全局初始化此配置
ImageLoader.getInstance().init(configuration);
}
/**
* 设置图片显示选项
*
* @return DisplayImageOptions 图片显示选项
*/
public static DisplayImageOptions setImgOptions() {
return new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565).cacheOnDisk(true)
// 缓存到sd卡
.cacheInMemory(true)
// 缓存到内存中
.showImageForEmptyUri(R.drawable.ic_launcher)
// 空uri时显示
.showImageOnFail(R.drawable.ic_launcher)
// 加载失败显示
.showImageOnLoading(R.drawable.ic_launcher)
// imageyuan
.displayer(new CircleBitmapDisplayer())// 加载时显示
.build();
}
}</span>
7.MyApplation
<span style="font-size:18px;">import com.example.month1.ImageloderUtils;
import android.app.Application;
public class MyApplation extends Application {
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
ImageloderUtils.initImgLoader(getApplicationContext());
}
}</span>
8.SecondActivity
<span style="font-size:18px;">import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import com.example.month1_adapter.MyBaseAdapter;
import com.example.month1_bean.News;
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 android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Xml;
import android.view.Menu;
import android.widget.ListView;
public class SecondActivity extends Activity {
private ListView listview;
ArrayList<News> myList = new ArrayList<News>();
String path = "http://www.oschina.net/action/api/tweet_detail";
private News news;
private int id;
private MyBaseAdapter myBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
listview = (ListView) findViewById(R.id.listview);
Intent intent = getIntent();
id = intent.getIntExtra("id", 0);
getpath();
}
public void getpath() {
HttpUtils httpUtils = new HttpUtils();
String mypath = path + "?id="+id;
httpUtils.send(HttpMethod.GET, mypath, new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
// TODO Auto-generated method stub
System.out.println("----------------" + arg1);
}
@Override
public void onSuccess(ResponseInfo<String> info) {
String result = info.result;
ByteArrayInputStream array = new ByteArrayInputStream(result
.getBytes());
System.out.println(result);
ArrayList<News> listnews = listnews(array);
myList.addAll(listnews);
if (myBaseAdapter == null) {
myBaseAdapter = new MyBaseAdapter(
SecondActivity.this, myList);
listview.setAdapter(myBaseAdapter);
} else {
myBaseAdapter.notifyDataSetChanged();
}
}
});
}
private ArrayList<News> listnews(InputStream inputStream) {
ArrayList<News> list = new ArrayList<News>();
XmlPullParser newPullParser = Xml.newPullParser();
try {
newPullParser.setInput(inputStream, "utf-8");
int eventype = newPullParser.getEventType();
while (eventype != XmlPullParser.END_DOCUMENT) {
String name = newPullParser.getName();
switch (eventype) {
case XmlPullParser.START_TAG:
if ("tweet".equals(name)) {
news = new News();
} else if ("id".equals(name)) {
news.setId(Integer.parseInt(newPullParser.nextText()));
} else if ("portrait".equals(name)) {
news.setPortrait(newPullParser.nextText());
} else if ("body".equals(name)) {
news.setBody(newPullParser.nextText());
} else if ("author".equals(name)) {
news.setAuthor(newPullParser.nextText());
} else if ("imgSmall".equals(name)) {
news.setImgSmall(newPullParser.nextText());
} else if ("imgBig".equals(name)) {
news.setImgBig(newPullParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("tweet".equals(name)) {
list.add(news);
news = null;
}
break;
default:
break;
}
eventype = newPullParser.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}</span>
9.activity_second.xml
<span style="font-size:18px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout></span>