android json分页,移动测试之异步任务+JSON解析+ListView分页
一、利用异步任务+JSON解析+ListView分页来实现网络访问数据显示在ListView中:
(一)、示例代码:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private ListView listView_main_newslist;
private LinearLayout layout_main_more;
private String urlString = "http://192.168.125.140:8080/AndroidServer/ShowQuestionlist?page=";
private boolean isBottom = false;
private int curPage = 1;
private SimpleAdapter adapter = null;
private List> totalList = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView_main_newslist = (ListView) findViewById(R.id.listView_main_newslist);
layout_main_more = (LinearLayout) findViewById(R.id.layout_main_more);
// 执行异步任务,获取劲松字符串
new MyTask(this).execute(urlString);
// 给listview设置适配器。数据源随着页面变化而不断追加新的数据
totalList = new ArrayList>();
adapter = new SimpleAdapter(this, totalList,
R.layout.item_listview_main, new String[] { "question" },
new int[] { R.id.text_item_listview_title });
listView_main_newslist.setAdapter(adapter);
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
isBottom = ((firstVisibleItem + visibleItemCount) == totalItemCount);
}
});
}
public void clickButton(View view) {
switch (view.getId()) {
case R.id.layout_main_more:
curPage++;
new MyTask(this).execute(urlString + curPage);
layout_main_more.setVisibility(View.GONE);
break;
default:
break;
}
}
class MyTask extends AsyncTask {
private Context context;
private ProgressDialog pDialog;
public MyTask(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setTitle("提示:");
pDialog.setMessage("数据加载中...");
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
@Override
protected byte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = new byte[8 * 1024];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result != null) {
// 开始执行json解析
try {
String data = new String(result, "utf-8");
// 将异步任务访问到的字节数组转成字符串,再通过json解析成list集合
List> list = jsonToList(data);
totalList.addAll(list);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "网络异常,加载失败!", Toast.LENGTH_SHORT)
.show();
}
pDialog.dismiss();
}
}
// 解析json字符串,生成list集合
private List> jsonToList(String jsonString) {
List> list = new ArrayList>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
Map map = new HashMap();
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String data = jsonObject2.getString("question");
map.put("question", data);
list.add(map);
}
return list;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
二、利用异步任务+JSON解析+ListView分页+自定义适配器 来实现网络访问数据显示在ListView中:
(一)、示例代码:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private ListView listView_main_newslist;
private LinearLayout layout_main_more;
private String urlString = "http://192.168.56.1:8080/AndroidServer/ShowQuestionlist?page=";
private boolean isBottom = false;
private int curPage = 1;
private MyAdapter adapter = null;
private List> totalList = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView_main_newslist = (ListView) findViewById(R.id.listView_main_newslist);
layout_main_more = (LinearLayout) findViewById(R.id.layout_main_more);
// 执行异步任务,获取劲松字符串
new MyTask(this).execute(urlString);
// 给listview设置适配器。数据源随着页面变化而不断追加新的数据
totalList = new ArrayList>();
// adapter = new SimpleAdapter(this, totalList,
// R.layout.item_listview_main, new String[] { "question" },
// new int[] { R.id.text_item_listview_title });
// 自定义适配器。
adapter = MyAdapter(this, totalList);
listView_main_newslist.setAdapter(adapter);
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
isBottom = ((firstVisibleItem + visibleItemCount) == totalItemCount);
}
});
}
public void clickButton(View view) {
switch (view.getId()) {
case R.id.layout_main_more:
curPage++;
new MyTask(this).execute(urlString + curPage);
layout_main_more.setVisibility(View.GONE);
break;
default:
break;
}
}
class MyTask extends AsyncTask {
private Context context;
private ProgressDialog pDialog;
public MyTask(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setTitle("提示:");
pDialog.setMessage("数据加载中...");
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
@Override
protected byte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = new byte[8 * 1024];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result != null) {
// 开始执行json解析
try {
String data = new String(result, "utf-8");
// 将异步任务访问到的字节数组转成字符串,再通过json解析成list集合
List> list = jsonToList(data);
totalList.addAll(list);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "网络异常,加载失败!", Toast.LENGTH_SHORT)
.show();
}
pDialog.dismiss();
}
}
// 解析json字符串,生成list集合
private List> jsonToList(String jsonString) {
List> list = new ArrayList>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
Map map = new HashMap();
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String data = jsonObject2.getString("question");
map.put("question", data);
list.add(map);
}
return list;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
class MyAdapter extends BaseAdapter {
private Context context;
private List> list = null;
public MyAdapter(Context context, List> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mHolder = null;
if (convertView == null) {
mHolder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.item_listview_main, parent, false);
mHolder.text_item_listview_title = (TextView) convertView
.findViewById(R.id.text_item_listview_title);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.text_item_listview_title.setText(list.get(position)
.get("question").toString());
return convertView;
}
class ViewHolder {
private TextView text_item_listview_title;
}
}
}
编辑:千锋软件测试
android json分页,移动测试之异步任务+JSON解析+ListView分页相关推荐
- 省市区json格式数据及异步请求json数据
省市区json数据 {"0": {"110000": "北京","120000": "天津",&qu ...
- android listview分页显示,Android应用中使用ListView来分页显示刷新的内容
点击按钮刷新1.效果如下: 实例如下: 上图的添加数据按钮可以换成一个进度条 因为没有数据所以我加了一个按钮添加到数据库用于测试:一般在服务器拉去数据需要一定的时间,所以可以弄个进度条来提示用户: ...
- Android 天气预报【解析XML / Json文件(2种方式:手动解析、Gson库解析)】
源码 [工程文件]:https://gitee.com/lwx001/Weather XML : activity_main.xml : <RelativeLayout xmlns:androi ...
- IOS开发基础之网易新闻环境搭建异步请求json,AFN网络封装第1天
IOS开发基础之网易新闻环境搭建异步请求json,AFN网络封装第1天 视频资料是2015年的,但是AFN是导入框架的关键文件,我尝试使用cocoapods安装最新的AFN,虽然成功了,但是版本太高, ...
- android 手动回收对象,Android Studio Studio回收列表中的JSON对象
我想在recyclerview中显示一些JSON对象,并且希望它们在日期之后排序,我该如何实现?下面是下载从JSON URL的数据的方法:Android Studio Studio回收列表中的JSON ...
- Android中使用HttpURLConnection实现GET POST JSON数据与下载图片
Android中使用HttpURLConnection实现GET POST JSON数据与下载图片 Android6.0中把Apache HTTP Client所有的包与类都标记为deprecated ...
- Android Junit 单元测试 Method wrap in org.json.JSONObject not mocked
今天在运行单元测试时报了一个错误 java.lang.RuntimeException: Method wrap in org.json.JSONObject not mocked. See http ...
- 前端 传表格多条数据 给后台接收 (HTML前端表格多条数据JSON封装后;异步提交到后台处理)
前端 传表格多条数据 给后台接收 (HTML前端表格多条数据JSON封装后:异步提交到后台处理) 1.多条数据采用checkBox 携带 //封装数据的对象var PayObj = { O_NBR:& ...
- 精通 Grails: 用 JSON 和 Ajax 实现异步 Grails
本文讨论 Grails 对于其互补技术 JSON 和 Ajax 的支持.在前几期的 精通 Grails 系列文章中,JSON 和 Ajax 都扮演支援者的角色,而这一次,它们担任主角.您将使用内置的 ...
最新文章
- linux常用的28个快捷键
- python print 不能立即打印输出 解决方法
- TCP/IP之TCP连接的建立与中止状态分析
- jQuery库中的变量$和其它类库的变量$冲突解决方案
- 小雪节气艺术字体设计PNG素材 | 希望可以温暖到你了
- SQL Server如何保证可空字段中非空值唯一
- Magedu2_3 linux文件目录
- 江苏实时分析评价系统项目总结报告
- JSP的执行过程及生命周期
- html弄多个按钮_html - 一个表单中的两个提交按钮
- vue和js点击下载pdf,word,png,jpg等格式的文件,解决点击下载pdf却是打开预览的问题
- 2022最好用压缩软件推荐,这三款就够了
- Git error: unable to create file xxx: Filename too long
- EEE802.11协议基础知识
- .click()与on('click',function())
- Gartner曾劭清:云计算市场依然存在太多变局
- 小钛掐指一算,今年的尖货市场不简单 | 活动预告
- 在GitHub上建立自己在线简历
- 动态内存管理(开辟以及释放动态内存空间)
- html转换markdownpad,MarkdownPad2导出HTML支持[TOC]
热门文章
- react svg 实现体温单 三测单
- Unity学习笔记 解决Cinemachine AutoDolly的虚拟相机在轨道上不按轨道前进方向运动的问题
- 数据仓库和数据集市的区别
- 关于等保和分保的应了解的
- 期末课程设计—学生成绩查询系统
- System.InvalidOperationException HResult=0x80131509 Message=ExecuteNonQuery 要求已打开且可用的 Connection
- 批量修改文件创建时间
- pclint的使用总结
- 达梦数据库实时主备集群的同步机制和切换机制
- go1.57安装框架iris12.1遇到的坑及解决