Android异步加载学习笔记之一:用AsyncTask加载服务器json数据

     我们知道在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;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值