移動測試之異步任務+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<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() {br/>@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() {br/>@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;
}
}
}

編輯:千鋒軟件測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章