我们知道在Android开发中,UI主线程不能执行耗时太久的操作,Activity一般是不超过5s,BroadCaseReceiver一般不超过10s,因为这些耗时操作不仅仅阻塞UI线程操作,还可能导致用户不想见到的ANR,所以我们需要使用异步操作。
我们通常用的异步操作有两种方式:
1:多线程或线程池异步加载,
2,AsyncTask异步任务操作(底层也是用的线程池)。
数据来源于慕课网:json数据地址:http://www.imooc.com/api/techer?type=4&num=30
首先定义加载数据的实体bean:
public class DataBean {
private String imgUrl;
private String title;
private String content;
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "DataBean [imgUrl=" + imgUrl + ", title=" + title + ", content=" + content + ", getImgUrl()=" + getImgUrl() + ", getTitle()=" + getTitle() + ", getContent()=" + getContent() + "]";
}
}
然后在Activity中加载数据,布局中就一个ListView,布局代码就过了:
public class MainActivity extends ActionBarActivity {
private ListView mListView;
private String url = "http://www.imooc.com/api/techer?type=4&num=30";
private DataAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.main_lv);
new MyAsyncTask().execute(url);
}
/**
* 解析返回的json数据为List<DataBean>
* @description:
* @author ldm
* @date 2015-8-10 下午8:44:19
*/
private List<DataBean> getGsonData(String url) {
List<DataBean> list = new ArrayList<DataBean>();
try {
String jsonStr = readStream(new URL(url).openStream());
JSONObject jobj = null;
DataBean bean = null;
jobj = new JSONObject(jsonStr);
JSONArray jsonArray = jobj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jobj = jsonArray.getJSONObject(i);
bean = new DataBean();
bean.setImgUrl(jobj.getString("picSmal"));
bean.setTitle(jobj.getString("name"));
bean.setContent(jobj.getString("description"));
list.add(bean);
}
}
catch (Exception e) {
e.printStackTrace();
}
return list;
}
private String readStream(InputStream is) {
InputStreamReader isr = null;
String result = "";
try {
isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null) {
result += line;
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 异步任务:将url中的数据访问
* @description:
* @author ldm
* @date 2015-8-10 下午8:43:52
*/
class MyAsyncTask extends AsyncTask<String, Void, List<DataBean>> {
@Override
protected List<DataBean> doInBackground(String... params) {
// TODO Auto-generated method stub
return getGsonData(params[0]);
}
@Override
protected void onPostExecute(List<DataBean> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mAdapter = new DataAdapter(MainActivity.this, result);//在数据加载成功后给ListView的适配器adapter设置数据
mListView.setAdapter(mAdapter);
}
}
}
接下来就是ListView的数据适配器:
public class DataAdapter extends BaseAdapter {
private Context mContext;
private List<DataBean> list;
public DataAdapter(Context mContext, List<DataBean> list) {
this.mContext = mContext;
this.list = list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int arg0, View view, ViewGroup arg2) {
ViewHolder holder=null;
if(view==null){
holder=new ViewHolder();
view=LayoutInflater.from(mContext).inflate(R.layout.item_layout, null);
holder.iv=(ImageView) view.findViewById(R.id.item_iv);
holder.titleTv=(TextView) view.findViewById(R.id.item_title);
holder.contentTv=(TextView) view.findViewById(R.id.item_content);
view.setTag(holder);
}else{
holder=(ViewHolder) view.getTag();
}
holder.titleTv.setText(list.get(arg0).getTitle());
holder.contentTv.setText(list.get(arg0).getContent());
holder.iv.setImageResource(R.drawable.ic_launcher);//先将图片展示固定图片,接下来就从网络获取
return view;
}
class ViewHolder {
TextView titleTv;
TextView contentTv;
ImageView iv;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
Android异步加载学习笔记之一:用AsyncTask加载服务器json数据
原文地址:http://blog.csdn.net/true100/article/details/47402773