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

来源:互联网 发布:淘宝上衣服尺码表 编辑:程序博客网 时间:2024/06/05 17:11
一、利用异步任务+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<Map<String, String>> 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<Map<String, String>>();

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);




// 给ListView设置滚动监听器

listView_main_newslist.setOnScrollListener(new OnScrollListener() {

@Override

public void onScrollStateChanged(AbsListView view, int scrollState) {

if (isBottom) {

layout_main_more.setVisibility(View.VISIBLE);

} else {
layout_main_more.setVisibility(View.GONE);

}

}

@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<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

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<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();

}

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<Map<String, String>> 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<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

public void onScrollStateChanged(AbsListView view, int scrollState) {

if (isBottom) {

layout_main_more.setVisibility(View.VISIBLE);

} else {

layout_main_more.setVisibility(View.GONE);

}

}

@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<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

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<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();

}

return null;

}

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

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;

}

}

}
0 0
原创粉丝点击