Android:异步网络加载JSON数据
2016-06-07 12:03
656 查看
转载 http://www.dengzhr.com/others/mobile/android/682
效果如下:
每次打开都可以获取最新的40条厚朴日志。
http://ce.sysu.edu.cn/hope/hopedairyjson/Index.aspx
【备注:获取前40条厚朴日志的JSON数据】
如图:
在AndroidManife.xml中,添加网络请求权限申请:
在主布局中,添加ListView,用于存放获取厚朴日志列表。
在item_layout.xml中设置ListView中每一个Adapter数据的显示样式。
NewsBean.java用于定义JSON返回数据的数据格式。
NewsAdapter.java将JSON数据返回值传递给BaseAdapter。
效果如下:
每次打开都可以获取最新的40条厚朴日志。
JSON数据源:
http://ce.sysu.edu.cn/hope/hopedairyjson/Index.aspx【备注:获取前40条厚朴日志的JSON数据】
如图:
添加权限申请
在AndroidManife.xml中,添加网络请求权限申请:<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml:
在主布局中,添加ListView,用于存放获取厚朴日志列表。<?xml version="1.0" encoding="utf-8"?> <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="wrap_content" tools:context=".MainActivity"> <ListView android:id="@+id/lv_main" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
item_layout.xml:
在item_layout.xml中设置ListView中每一个Adapter数据的显示样式。<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="title" android:maxLines="1" android:textSize="14dp" android:layout_alignParentLeft="true"/> <TextView android:id="@+id/tv_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2015-11-11" android:layout_alignParentRight="true" android:textSize="12dp"/> </RelativeLayout> <TextView android:id="@+id/tv_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ContentContentContentContent" android:textSize="10dp"/> </LinearLayout>
NewsBean.java:
NewsBean.java用于定义JSON返回数据的数据格式。/* * 声明用JSON获取的数据源 * */ public class NewsBean { public String newsTitle; public String newsDate; public String newsContent; }
NewsAdapter.java:
NewsAdapter.java将JSON数据返回值传递给BaseAdapter。import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; /* * 将JSON数据返回值传递给BaseAdapter * */ public class NewsAdapter extends BaseAdapter { // 声明用于装载JSON数据返回值 private List<NewsBean> mList; // 声明Inflater,用于将Layout转为View private LayoutInflater mInflater; /* * 将JSON返回的数据传递给BaseAdapter * */ public NewsAdapter(Context context, List<NewsBean> data) { mList = data; mInflater = LayoutInflater.from(context); } /* * 返回ListView中Adapter的数据长度 * */ @Override public int getCount() { return mList.size(); } /* * 返回当前索引Adapter数据 * */ @Override public Object getItem(int position) { return mList.get(position); } /* * 返回当前Adapter数据的索引 * */ @Override public long getItemId(int position) { return position; } /* * 更改当前ListView * */ @Override public View getView(int position, View convertView, ViewGroup parent) { /* * 为ListView中的数据定义装载的View容器 * */ ViewHolder viewHolder = null; if(convertView == null) { viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.item_layout, null); viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title); viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tv_date); viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } /* * 将Adapter中的数据添加到View容器中 * */ viewHolder.tvDate.setText(mList.get(position).newsDate); viewHolder.tvTitle.setText(mList.get(position).newsTitle); viewHolder.tvContent.setText(mList.get(position).newsContent); return convertView; } /* * 定义Adapter数据 * */ class ViewHolder { public TextView tvTitle, tvContent, tvDate; } }
MainActivity.java:
import android.os.Bundle; import android.app.Activity; import android.os.AsyncTask; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { // 声明ListView private ListView mListView; // 定义JSON数据的来源URL private static String URL = "http://ce.sysu.edu.cn/hope/hopedairyjson/Index.aspx"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 定义用于装载JSON数据的ListVIew mListView = (ListView) findViewById(R.id.lv_main); // 实例化AsyncTask,并请求网络数据加载 new NewsAsyncTask().execute(URL); } /* * 创建AsyncTask用于请求网络数据加载 * */ class NewsAsyncTask extends AsyncTask<String, Void, List<NewsBean>> { @Override protected List<NewsBean> doInBackground(String... params) { try { return getJsonData(params[0]); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(List<NewsBean> newsBeans) { super.onPostExecute(newsBeans); /* * 实例化Adapter,为ListView填充数据 * */ NewsAdapter adapter = new NewsAdapter(MainActivity.this, newsBeans); mListView.setAdapter(adapter); } } /* * 根据url来获取并解析JSON数据 * */ private List<NewsBean> getJsonData(String url) throws IOException { List<NewsBean> newsBeanList = new ArrayList<>(); /* * 获取JSON并解析JSON * * JSON数据格式为: * { "data":[ * { "name": "myName", "content": "MyContent", "date": "2015-11-18" }, * {"name": "myName", "content": "MyContent", "date": "2015-11-18" } * ] } * */ String jsonString; try { jsonString = readStream(new URL(url).openStream()); JSONObject jsonObject; NewsBean newsBean; jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("data"); /* * 逐行解析JSON数据 * */ for(int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); newsBean = new NewsBean(); newsBean.newsTitle = jsonObject.getString("name"); newsBean.newsDate = jsonObject.getString("date"); newsBean.newsContent = jsonObject.getString("content"); newsBeanList.add(newsBean); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return newsBeanList; } /* * 读取输入数据流 * */ private String readStream(InputStream is) { InputStreamReader isr; String result = ""; try { String line = ""; isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); while((line = br.readLine()) != null) { result += line; } }catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
相关文章推荐
- Android中的网络编程
- [置顶] viewPager+photoView实现网络图片加载左右滑动+手势缩放功能+滑动到下一页其他页面恢复默认大小
- 软件定义网络学习总结
- TCP为什么要三次握手,不是两次四次?
- openStream打开网络地址获取文件流
- C++线程与网络接口技术(第一节:线程及其创建,调度与回收知识)
- C# 监听HTTP请求
- Apache http安装
- (转)Go和HTTPS
- 计算机网络体系结构
- 详解ssh/https远程连接Git服务器
- 一个单页网站也能流量过亿!这个网络穿透方法被90%的站长忽略了
- 计算机网络体系结构
- 图解使用Telnet程序手工发送邮件
- C#模拟http 发送post或get请求的简单实例
- RxVolley使用文档 —— RxVolley = Volley + RxJava + OkHttp
- RxVolley使用文档 —— RxVolley = Volley + RxJava + OkHttp
- 在WinForm中发送HTTP请求的实现方法
- 架设证书服务器 及 让IIS启用HTTPS服务
- ios https单向验证