异步任务+JSON解析+ListView分页

异步任务+JSON解析+ListView分页

一、利用异步任务+JSON解析+ListView分页来实现网络访问数据显示在ListView中:
(一)、示例代码:

publicclass MainActivity extends Activity {
privatestaticfinal 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=";
privatebooleanisBottom = false;
privateintcurPage = 1;
private SimpleAdapter adapter = null;
private List<Map<String, String>> totalList = null;

      @Override
protectedvoid 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<Map<String, String>>();
adapter = new SimpleAdapter(this, totalList,R.layout.item_listview_main, new String[] { "question" },
newint[] { R.id.text_item_listview_title });
               listView_main_newslist.setAdapter(adapter);

               // 给ListView设置滚动监听器
listView_main_newslist.setOnScrollListener(new OnScrollListener() {
                   
@Override
publicvoid onScrollStateChanged(AbsListView view, int scrollState) {
if (isBottom) {
layout_main_more.setVisibility(View.VISIBLE);
                         } else {
layout_main_more.setVisibility(View.GONE);
                         }
                 }

           @Override
publicvoid onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
isBottom = ((firstVisibleItem + visibleItemCount) == totalItemCount);
            }
       }

publicvoid 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<String, Void, byte[]> {
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
protectedvoid onPreExecute() {
super.onPreExecute();
pDialog.show();
               }

               @Override
protectedbyte[] 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 = newbyte[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();
                               }
                       }
returnnull;
               }

               @Override
protectedvoid onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result != null) {
                            // 开始执行json解析
try {
                                       String data = new String(result, "utf-8");
                                       // 将异步任务访问到的字节数组转成字符串,再通过json解析成list集合
                                       List<Map<String, String>> 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<Map<String, String>> jsonToList(String jsonString) {
               List<Map<String, String>> list = new ArrayList<Map<String, String>>();
try {
                       JSONObject jsonObject = new JSONObject(jsonString);
                       JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
                               Map<String, String> map = new HashMap<String, String>();
                               JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                               String data = jsonObject2.getString("question");
                               map.put("question", data);
                               list.add(map);
                       }
return list;
               } catch (JSONException e) {
                       e.printStackTrace();
               }
returnnull;
       }
}

二、利用异步任务+JSON解析+ListView分页+自定义适配器 来实现网络访问数据显示在ListView中:
(一)、示例代码:

publicclass MainActivity extends Activity {
privatestaticfinal 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=";
privatebooleanisBottom = false;
privateintcurPage = 1;
private MyAdapter adapter = null;
private List<Map<String, String>> totalList = null;
       @Override
protectedvoid 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<Map<String, String>>();
              // 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);

            // 给ListView设置滚动监听器
listView_main_newslist.setOnScrollListener(new OnScrollListener() {
                   @Override
publicvoid onScrollStateChanged(AbsListView view, int scrollState) {
if (isBottom) {
layout_main_more.setVisibility(View.VISIBLE);
                            } else {
layout_main_more.setVisibility(View.GONE);
                            }
                       }

                   @Override
publicvoid onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
isBottom = ((firstVisibleItem + visibleItemCount) == totalItemCount);
                       }
               });
       }

publicvoid 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<String, Void, byte[]> {
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
protectedvoid onPreExecute() {
super.onPreExecute();
pDialog.show();
               }

               @Override
protectedbyte[] 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 = newbyte[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();
                               }
                       }
returnnull;
               }

               @Override
protectedvoid onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result != null) {
                               // 开始执行json解析
try {
                                       String data = new String(result, "utf-8");
                                    // 将异步任务访问到的字节数组转成字符串,再通过json解析成list集合
                                       List<Map<String, String>> 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<Map<String, String>> jsonToList(String jsonString) {
               List<Map<String, String>> list = new ArrayList<Map<String, String>>();
try {
                       JSONObject jsonObject = new JSONObject(jsonString);
                       JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
                               Map<String, String> map = new HashMap<String, String>();
                               JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                               String data = jsonObject2.getString("question");
                               map.put("question", data);
                               list.add(map);
                       }
return list;
               } catch (JSONException e) {
                       e.printStackTrace();
               }
returnnull;
       }

class MyAdapter extends BaseAdapter {
private Context context;
private List<Map<String, String>> list = null;

public MyAdapter(Context context, List<Map<String, String>> list) {
this.context = context;
this.list = list;
               }

              @Override
publicint getCount() {
returnlist.size();
               }

              @Override
public Object getItem(int position) {
returnlist.get(position);
               }

              @Override
publiclong 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;
               }
       }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值