您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection下载数据,JSON解析数据, BaseAdapter 适配数据。

2016-05-20 15:32 537 查看
实现思路:

1.得到一个获取数据的网络接口,通过接口下载到数据。

2.通过JSON解析得到我们想要的数据。

3.通过 BaseAdapter 适配到界面进行展示。

实现效果展示:



不多说,直接上代码代码展示。

主页面代码:

public class MainActivity extends Activity {
List<Newz> newzList = new ArrayList<>();
String urlString = "http://www.tngou.net/api/top/list?page=1&rows=10";//接口
private ListView listView;
private MyDaseAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
//1下载数据 2解析数据 3 适配数据
downloadPaserData();
adapter = new MyDaseAdapter (this,newzList);
listView.setAdapter(adapter);
}

private void downloadPaserData() {
// TODO Auto-generated method stub
//开始异步任务下析数据,4.注册一个监听器对象,获取结果,通过接口回调的方法返回,数据下载解析完返回.
//数据返回之后,记得把新的数据存入list集合中,还有更新适配器对象adapter
MyAysncTaskJson task = new MyAysncTaskJson(new OnTaskConpletedListener(){

@Override
public void onTaskConpleted(List<Newz> retList) {
// TODO Auto-generated method stub
newzList.addAll(retList);
adapter.notifyDataSetChanged();//更新
Log.e("下载解析完返回的数据", retList.toString());
}});

task.execute(urlString);
}


1.下载数据代码:

public class MyAysncTaskJson extends AsyncTask<String , Void, List<Newz>> {
//a自定义一个接口
public interface OnTaskConpletedListener{
void  onTaskConpleted(List<Newz> retList);//c声明一个方法,当任务完成时调用这个方法,把数据回调
}
//b创建该类的构造方法,传入接口的对象,用于接收解析好的数据
private OnTaskConpletedListener listener;
public MyAysncTaskJson(OnTaskConpletedListener listener) {
// TODO Auto-generated constructor stub
this.listener = listener;
}
//doInBackground:进行下载解析
@Override
protected List<Newz> doInBackground(String... params) {
// TODO Auto-generated method stub
//下载
String urlString = params[0];
String jsonString = HuttpUtil.download(urlString);
//Log.e("下载得到的数据:", jsonString);
List<Newz> newzList = JsonParser.parser(jsonString);
return newzList;

}

//onPostExecute:下载到结果result
@Override
protected void onPostExecute(List<Newz> result) {
// TODO Auto-generated method stub
if(listener!=null&&result!=null){
listener.onTaskConpleted(result);//d把解析到的结果返回接口
}
}
}


1.1:HttpURL下载代码:

public static String download(String urlString) {
// TODO Auto-generated method stub
//下载
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StringBuffer sbBuffer = new StringBuffer();
InputStream inputStream = connection.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream));

while(true){
String line = bfr.readLine();
if(line==null){
break;
}
sbBuffer.append(line);
}

return sbBuffer.toString();

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

public static Bitmap downLoadImage(String urlString) {
// TODO Auto-generated method stub
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
return bitmap;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

}


1.2:图片下载的代码:

public class MyImageTask  extends AsyncTask<String, Void, Bitmap>{
private ImageView image2;
public MyImageTask(ImageView image2) {
// TODO Auto-generated constructor stub
this.image2 = image2;
}
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
//下载图片
Bitmap bitmap = HuttpUtil.downLoadImage(params[0]);

return bitmap;
//return null;
}
@Override
protected void onPostExecute(Bitmap result) {

if(result!=null){
image2.setImageBitmap(result);
}
}

}


2.JSON解析数据代码:

public class JsonParser {
public static List<Newz> parser(String jsonString) {
// TODO Auto-generated method stub
//解析
if(jsonString==null){
return null;
}
List<Newz> newzList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("tngou");//数组的关键字
for (int i = 0; i < jsonArray.length(); i++) {
//JSONArray jsontimeObject = jsonArray.getJSONArray(i);
JSONObject tempJsonObject = jsonArray.getJSONObject(i);//注意,返回的是object类型
Newz newz = new Newz();
//全部用getString
newz.setCount(tempJsonObject.getString("count"));
newz.setDescription(tempJsonObject.getString("description"));
newz.setImg("http://tnfs.tngou.net/image"+(tempJsonObject.getString("img")));
newz.setRocunt(tempJsonObject.getString("rcount"));
newz.setTime(tempJsonObject.getString("time"));
newz.setTitle(tempJsonObject.getString("title"));
newzList.add(newz);

}
return newzList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

}


3 .适配数据的代码:

public class MyDaseAdapter extends BaseAdapter {
private Context context;
private List<Newz> newzList;
public MyDaseAdapter(Context context, List<Newz> newzList) {
// TODO Auto-generated constructor stub
this.context = context;
this.newzList = newzList;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return newzList.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return newzList.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

//进行适配
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//1concertView:系统自带了一个子视图,
//2创建一个ViewHodler类,把所有的listview_layout控件添加到ViewHodler容器中。
//3给ViewHodler容器添加解析到的值
//4再把ViewHodler容器中的控件全部赋值给convertView中
ViewHodler viewHodler = null;
if(convertView==null){//如果子视图时空布局,就加载一个
convertView = LayoutInflater.from(context).inflate(R.layout.listview_layout, null);
viewHodler = new ViewHodler();
//a 找到控件
TextView aTextView =(TextView) convertView.findViewById(R.id.title);
TextView bTextView =(TextView) convertView.findViewById(R.id.time);
TextView cTextView =(TextView) convertView.findViewById(R.id.description);
TextView dTextView =(TextView) convertView.findViewById(R.id.count);
TextView eTextView =(TextView) convertView.findViewById(R.id.rcount);
ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
//b 把控件赋值给ViewHold这个容器
viewHodler.titleTextView = aTextView;
viewHodler.timetTextView = bTextView;
viewHodler.descriptiontTextView = cTextView;
viewHodler.counttTextView = dTextView;
viewHodler.rcountTextView = eTextView;
viewHodler.image = imageView;
//c 把viewHodler这个对象设置给convertView
convertView.setTag(viewHodler);
}else {//d 如果convertView被复用,那么就赋值给convertView
viewHodler = (ViewHodler) convertView.getTag();
}
//e 给ViewHodler设置数据
viewHodler.titleTextView.setText("新闻标题:"+newzList.get(position).getTitle());
viewHodler.timetTextView.setText("发布时间:"+newzList.get(position).getTime());
viewHodler.descriptiontTextView.setText("新闻内容:"+newzList.get(position).getDescription());
viewHodler.counttTextView.setText("访问数:"+newzList.get(position).getCount());
viewHodler.rcountTextView.setText("评论数:"+newzList.get(position).getRocunt());

//如果对应的position位置处有图片,就异步下载图片,然后显示
//如果没有图,设置一张默认图
ImageView image2 = viewHodler.image;//找到image对象
String imageUrl= newzList.get(position).getImg();
//Log.e("图片的url地址", imageUrl);
if(imageUrl.equals("http://tnfs.tngou.net/image")){
viewHodler.image.setImageResource(R.drawable.ic_launcher);
}else {
//如果有图片,就进行异步下载
MyImageTask Task = new MyImageTask(image2);
Task.execute(imageUrl);//把图片的网址传送过去
}

return convertView;
}
class ViewHodler{
TextView titleTextView,timetTextView,descriptiontTextView,counttTextView,rcountTextView;
ImageView image;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: