Android项目开发全程(四)-- 将网络返回的json字符串轻松转换成listview列表

时间:2022-08-21 09:23:45

  前面几篇博文介绍了从项目搭建到获取网络字符串,对一个项目的前期整体工作进行了详细的介绍,本篇接着上篇介绍一下怎么样优雅将网络返回的json字符串轻松转换成listview列表。

  先上图,看一下效果。

  Android项目开发全程(四)-- 将网络返回的json字符串轻松转换成listview列表       Android项目开发全程(四)-- 将网络返回的json字符串轻松转换成listview列表       Android项目开发全程(四)-- 将网络返回的json字符串轻松转换成listview列表

  包括下拉刷新和上拉加载更多两个功能,怎样还算可以吧~,比起前几篇博文中的那一大片一大片的“乱码”看起来是不是舒服多了。

一、对界面面布局

  1、Android默认的标题栏不太好看,咱们需要换成自己的。在AndroidManifest.xml文件中将APP主题设为NoTitleBar

 <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
</application>

  2、然后在每个局部文件中加上自己创建的标题,为了以后便于管理,最好将标题作为一个单独的布局文件(title_layout.xml),然后通过include引用。

 <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="44dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/app_title"
android:layout_width="fill_parent"
android:layout_height="44dp"
android:gravity="center"
android:background="#FFA500"
android:textColor="#FFF"
android:textSize="20dp"
android:text="@string/app_name" />
</LinearLayout>

  3、创建主界面(activity_main.xml)

 <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="match_parent"
android:background="#ededed"
android:orientation="vertical" >
 <!--引用标题栏-->
<include layout="@layout/title_layout"/>
<!-- 第三方类库的listview,可下拉刷新,上拉加载更多 -->
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/pull_refresh_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:layout_marginTop="3dp"
android:cacheColorHint="#00000000"
android:divider="@null"
android:fadingEdge="none"
android:fastScrollEnabled="false"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false"
android:scrollbars="none"
android:smoothScrollbar="true"/>
</LinearLayout>

  这里通过include引用了title_layout.xml文件,listview控件使用的第三方类库PullToRefresh,下载时会一并给出。

  4、创建listview的item布局(item_main.xml)

 <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:paddingTop="3dp"
android:paddingBottom="3dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:orientation="vertical" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@drawable/bg_shape"
android:orientation="vertical" > <TextView
android:id="@+id/tv_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#3b3d42"
android:textSize="16dp" /> <TextView
android:id="@+id/tv_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:textColor="#636251"
android:textSize="12dp" />
<TextView
android:id="@+id/tv_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#636251"
android:textSize="16dp"
android:layout_marginTop="8dp" />
</LinearLayout>
</LinearLayout>

二、创建Adapter(MainAdapter.java)

 public class MainAdapter extends BaseAdapter {
private Context context;
private List<Map<String, Object>> list;
private LayoutInflater inflater;
public MainAdapter(Context context, List<Map<String, Object>> list) {
this.context = context;
inflater = inflater.from(context);
this.list = list;
}
@Override
public int getCount() {
return list.size();
} @Override
public Object getItem(int arg0) {
return list.get(arg0);
} @Override
public long getItemId(int arg0) {
return arg0;
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
Map<String, Object> map = list.get(position);
if(holder == null){
holder = new Holder();
convertView = inflater.inflate(R.layout.item_main, null);
holder.title = (TextView) convertView.findViewById(R.id.tv_title);
holder.time = (TextView) convertView.findViewById(R.id.tv_time);
holder.content = (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(holder);
}
holder.title.setText(map.get("title").toString());
holder.time.setText(map.get("publishDate").toString());
holder.content.setText(map.get("content").toString());
return convertView;
} class Holder {
public TextView title;
public TextView time;
public TextView content;
}
}

  这里的MainAdapter继承了BaseAdapter,为listview提供适配器。

三、在MainActivity操作数据(分步讲解)

  1、初始化pullRefreshList(是一个PullToRefreshListView,第三方类库PullToRefresh,可上拉刷新,下拉加载更多)

 //初始化pullRefreshList
public void initListView(){
pullRefreshList.setMode(Mode.BOTH);
layoutProxy = pullRefreshList.getLoadingLayoutProxy(true, false);
layoutProxy.setPullLabel("下拉刷新");
layoutProxy.setReleaseLabel("松开立即刷新");
layoutProxy.setRefreshingLabel("正在载入");
layoutProxybottom = pullRefreshList.getLoadingLayoutProxy(false, true);
layoutProxybottom.setPullLabel("上拉加载更多");
layoutProxybottom.setReleaseLabel("松开立即刷新");
layoutProxybottom.setRefreshingLabel("正在载入");
pullRefreshList.setOnRefreshListener(new MyRefresh());
listView = pullRefreshList.getRefreshableView();
lists = new ArrayList<Map<String,Object>>();
adapter = new MainAdapter(getApplicationContext(), lists);
listView.setAdapter(adapter);
}

  2、设置pullRefreshList的刷新监听器,当上拉是表示刷新,将参数page设为第一页,提交请求。当下拉时表示加载更多,将page+1,然后提交请求。

 class MyRefresh implements OnRefreshListener2<ListView>{
    //上拉是回调此方法
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
page = 1;
getNetData.getLaughBy360(REQUEST_360LAUGH_CODE, page + "");
}
    //下拉时回调此方法
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
if(page < 34){  //目前接口中一个有34页数据
page += 1;
getNetData.getLaughBy360(REQUEST_360LAUGH_CODE, page + "");
mHandler.sendEmptyMessage(DIALOG_SHOW);
} else {
pullRefreshList.onRefreshComplete();
Toast.makeText(getApplicationContext(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
}
}
}

  3、在网络请求的回调方法中,利用jackson工具的ObjectMapper可以很容易的将json字符串转换成Map(也可根据需要转换成List、对象等等)

 public void onCallBackSuccessed(int notify, String result) {
if(notify == REQUEST_360LAUGH_CODE){
try {
//使用Jackson工具的ObjectMapper直接将json字符串转换成Map格式
Map<String, Object> map = objectMapper.readValue(result, Map.class);
List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("jokes");
if(page == 1) {
lists.clear();
}
if(list.size() == 0){
Toast.makeText(getApplicationContext(), "木有笑话了", Toast.LENGTH_SHORT).show();
} else {
lists.addAll(list);
//改变adapter数据
adapter.notifyDataSetChanged();
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
mHandler.sendEmptyMessage(DIALOG_CONCEL);
pullRefreshList.onRefreshComplete();
}

  分析一下,这里每次从网络上获取的结果转成后都先加入到一个临时的list中,当page=1时,说明此事是上拉刷新或者首次请求。这时候将直接将lists清空来接受最新数据,当page !=1 时说明是加载更多的请求,无需清空lists,如果新返回的数据不为空则将list加入到lists中,然后通知adapter数据改变。

  别忘了设置onRefreshComplete完成刷新状态。

  最后,整个的MainActivity.java如下:

 package com.laughdemo.main;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.tsz.afinal.annotation.view.ViewInject;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.laughdemo.adapter.MainAdapter;
import com.laughdemo.http.DataCallBack;
import com.laughdemo.http.GetNetData;
import com.laughdemo.utils.Constants;
/**
* 主窗体类
* @author 刘伟 2015.7.3
*/
public class MainActivity extends BaseActivity implements Constants, DataCallBack{
final String TAG = "MainActivity";
GetNetData getNetData;
MainAdapter adapter;
private int page = 1;
ListView listView;
List<Map<String, Object>> lists;
private ILoadingLayout layoutProxy;
private ILoadingLayout layoutProxybottom;
@ViewInject(id=R.id.pull_refresh_list) PullToRefreshListView pullRefreshList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initListView();
getNetData = new GetNetData(this);
getNetData.getLaughBy360(REQUEST_360LAUGH_CODE, page + "");
mHandler.sendEmptyMessage(DIALOG_SHOW);
} //初始化pullRefreshList
public void initListView(){
pullRefreshList.setMode(Mode.BOTH);
layoutProxy = pullRefreshList.getLoadingLayoutProxy(true, false);
layoutProxy.setPullLabel("下拉刷新");
layoutProxy.setReleaseLabel("松开立即刷新");
layoutProxy.setRefreshingLabel("正在载入");
layoutProxybottom = pullRefreshList.getLoadingLayoutProxy(false, true);
layoutProxybottom.setPullLabel("上拉加载更多");
layoutProxybottom.setReleaseLabel("松开立即刷新");
layoutProxybottom.setRefreshingLabel("正在载入");
pullRefreshList.setOnRefreshListener(new MyRefresh());
listView = pullRefreshList.getRefreshableView();
lists = new ArrayList<Map<String,Object>>();
adapter = new MainAdapter(getApplicationContext(), lists);
listView.setAdapter(adapter);
} class MyRefresh implements OnRefreshListener2<ListView>{ @Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
page = 1;
getNetData.getLaughBy360(REQUEST_360LAUGH_CODE, page + "");
} @Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
if(page < 34){
page += 1;
getNetData.getLaughBy360(REQUEST_360LAUGH_CODE, page + "");
mHandler.sendEmptyMessage(DIALOG_SHOW);
} else {
pullRefreshList.onRefreshComplete();
Toast.makeText(getApplicationContext(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCallBackSuccessed(int notify, String result) {
if(notify == REQUEST_360LAUGH_CODE){
try {
//使用Jackson工具的ObjectMapper直接将json字符串转换成Map格式
Map<String, Object> map = objectMapper.readValue(result, Map.class);
List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("jokes");
if(page == 1) {
lists.clear();
}
if(list.size() == 0){
Toast.makeText(getApplicationContext(), "木有笑话了", Toast.LENGTH_SHORT).show();
} else {
lists.addAll(list);
//改变adapter数据
adapter.notifyDataSetChanged();
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
mHandler.sendEmptyMessage(DIALOG_CONCEL);
pullRefreshList.onRefreshComplete();
}
@Override
public void onCallBackFailed(int notify) {
mHandler.sendEmptyMessage(DIALOG_CONCEL);
pullRefreshList.onRefreshComplete();
Toast.makeText(getApplicationContext(), "网络连接失败", Toast.LENGTH_LONG).show();
}
}

到这里,这个小项目的整个流程也可以算是介绍完了。有需要项目源码的可以直接留下邮箱索要,也可以去下载:http://download.csdn.net/detail/u012950035/8871581

本篇博文是在前几篇的基础上接着做的,如有不明白的地方还需参考前几篇: