Json解析小案例

本文Json解析荔枝新闻
MainActivity中的代码:

package org.moblie.train.zday09_json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.moblie.train.zday09_json_MyUtils.HttpURLConnHelper;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private String jsonUrl = "http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=20&pageIndex=";
    private ListView listView;
    private MyAdapter adapter;
    private List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    private boolean isBottom;
    private int currentPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化ListView
        initViews();
        // 完成网络请求,通过异步任务,在子线程完成
        loadNetworkData();
    }

    private void loadNetworkData() {
        new MyTask().execute(jsonUrl + currentPage);
    }

    private void initViews() {
        listView = (ListView) findViewById(R.id.listView_Main);
        adapter = new MyAdapter(list, this);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isBottom && scrollState == SCROLL_STATE_IDLE) {
                    // 已经滑动到最底部。此时需要将页数加1,再重新请求
                    currentPage++;
                    loadNetworkData();
                }
            }

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

    public List<Map<String, String>> jsonStringToList(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            if (jsonObject.getString("status").equals("ok")) {
                JSONObject jsonObject_paramz = jsonObject
                        .getJSONObject("paramz");
                JSONArray jsonArray_feeds = jsonObject_paramz
                        .getJSONArray("feeds");
                // 解析JSONArray要遍历
                for (int i = 0; i < jsonArray_feeds.length(); i++) {
                    JSONObject jsonObject_feed = jsonArray_feeds
                            .getJSONObject(i);
                    JSONObject jsonObject_data = jsonObject_feed
                            .getJSONObject("data");
                    String jsonString_subject = jsonObject_data
                            .getString("subject");
                    String jsonString_summary = jsonObject_data
                            .getString("summary");
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("subject", jsonString_subject);
                    map.put("summary", jsonString_summary);
                    list.add(map);
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    class MyTask extends AsyncTask<String, Integer, List<Map<String, String>>> {

        @Override
        // 在子线程中完成的方法
        protected List<Map<String, String>> doInBackground(String... params) {
            // 网络请求返回的byte数组
            // 参数即URL
            /** [此处用到的网络请求工具类详见博客](http://blog.csdn.net/iblade/article/details/50488749) */
            byte[] data = HttpURLConnHelper.loadByteFromURL(params[0]);
            if (data != null) {
                String jsonString = new String(data);
                List<Map<String, String>> li = jsonStringToList(jsonString);
                return li;
            } else {// 如果data为空,即网络数据请求失败
                Toast.makeText(MainActivity.this, "网络异常,请检查网络",
                        Toast.LENGTH_SHORT);
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<Map<String, String>> li) {
            super.onPostExecute(li);
            list.addAll(li);
            adapter.notifyDataSetChanged();
        }
    }
}

MyAdapter中的代码:

package org.moblie.train.zday09_json;

import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
    private List<Map<String, String>> list;
    private Activity activity;

    public MyAdapter(List<Map<String, String>> list, Activity activity) {
        super();
        this.list = list;
        this.activity = activity;
    }

    @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 holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = activity.getLayoutInflater().inflate(
                    R.layout.item_listview_main, parent, false);
            holder.subjectView = (TextView) convertView
                    .findViewById(R.id.textSuject);
            holder.summaryView = (TextView) convertView
                    .findViewById(R.id.textSummary);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.subjectView.setText(list.get(position).get("subject"));
        holder.summaryView.setText(list.get(position).get("summary"));

        return convertView;
    }

    class ViewHolder {
        private TextView subjectView;
        private TextView summaryView;

    }
}

item_listview_activity.xml中的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" >

    <TextView  android:id="@+id/textSuject" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="标题" />

    <TextView  android:id="@+id/textSummary" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="内容" />

</LinearLayout>

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:orientation="vertical" >

    <ListView  android:id="@+id/listView_Main" android:layout_width="match_parent" android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

我们的数据源来自网络
所以一定不要忘了在清单文件中为其设置连接网络权限
清单文件中的代码:

   <uses-sdk  android:minSdkVersion="8" android:targetSdkVersion="14" />
    <uses-permission android:name="android.permission.INTERNET"/>

你可能感兴趣的:(json,异步任务)