Json_城市三级列表实现(两种样式)

项目:cityjsonlist

思路:

  • 1.通过IO流读取本地asset目录下的cityjson.json文件返回String类型的response。
  • 2.通过gson解析将数据保存在List cityResultLists中
  • 3.将获取的省、城市、区/县保存在对应的List中,为了产生级联效果,将单个province(string)与获取完整的city的List保存在HashMap中,产生一一对应关系
    -------------以上步骤为保存数据-----------
  • 4.省份spinner控件首先设置数据样式,同时updateCity方法获取存在HashMap省份对应的city的List,以此类推。

在此过程中出现空指针异常错误
有两方面的原因:1. mContext未赋值 2. 存放的数据变量填写错误。

Json_城市三级列表实现(两种样式)_第1张图片
Paste_Image.png
项目:TestcityLists2

在先前项目中把存储省份的操作提取为单独的一个方法:

package com.example.testcitylists.db;
import android.content.Context;
import android.widget.ArrayAdapter;

/**
 * 查询城市信息类
 */
public class CityDbQuery {

    private static final String TAG = "TAG";
    private String city_url;
    private Context mContext;
    //适配器
    private ArrayAdapter mProAdapter;
    private ArrayAdapter mCityAdapter;
    private ArrayAdapter mAreaAdapter;

    //存放城市信息的数组
    private String[] mProvinceDatas;
    private String[] mCityDatas;
    private String[] mAreaDatas;


    //存放 province — city — area 相对应的HashMap
    private Map mCityMaps;
    private Map mAreaMaps;


    public CityDbQuery(Context context) {
        this.mContext=context;
    }

    /**
     * 本地文件解析
     */
    public void beginLocalJsonParse() {
        mAreaMaps = new HashMap<>();
        mCityMaps = new HashMap<>();

        String response = HttpLocalUtils.sendRequest(mContext, "cityjson.json");

        Gson gson = new Gson();
        List cityResultLists = gson.fromJson(response, new TypeToken>() {
        }.getType());

        mProvinceDatas = new String[cityResultLists.size()];
        String province = null;

        for (int i = 0; i < cityResultLists.size(); i++) {
            CityAllResults cityAllResults = cityResultLists.get(i);
            //获取省份
            if (cityAllResults.getProvice() != null) {
                province = cityAllResults.getProvice();
                //存在 省 数组中
                mProvinceDatas[i] = province;
            } else {
                mProvinceDatas[i] = "unknown province";
            }

            List cityLists = cityAllResults.getCityLists();

            mCityDatas = new String[cityLists.size()];
            for (int j = 0; j < cityLists.size(); j++) {

                CityAllResults.CityBean cityBean = cityLists.get(j);
                //获取城市信息
                String city = cityBean.getCity();
                //存在 城市 数组中
                mCityDatas[j] = city;
                List areaLists = cityBean.getAreaLists();
                //Log.i(TAG, "city------" + mCityDatas[j]);

                mAreaDatas = new String[areaLists.size()];
                for (int k = 0; k < areaLists.size(); k++) {

                    //找到区/县信息
                    String area = areaLists.get(k);
                    //存在area数组中
                    mAreaDatas[k] = area;
                    // Log.w(TAG, "area------" + mAreaDatas[k]);

                }

                //在 area 取出完之后,将mAreaDatas和对应的city存在mAreaMaps中,有一一对应关系
                mAreaMaps.put(city, mAreaDatas);
            }

            //在 city 取出完之后,将province和对应的mAreaDatas存在mCityMaps中,有一一对应关系
            mCityMaps.put(province, mCityDatas);
        }

    }

    /**
     * 获取省份信息
     * @return:返回list<省>
     */
    public List loadProvince(){
        Listlist=new ArrayList<>();
        for (int i=0;i
     */
    public ListloadCity(String selectedPro){
        Listlist=new ArrayList<>();
        String[] cities = mCityMaps.get(selectedPro);
        for (int i=0;i
     */
    public ListloadArea(String selectedCity){
        Listlist=new ArrayList<>();
        String[] areas = mAreaMaps.get(selectedCity);
        for (int i=0;i

关于主activity文件

package com.example.testcitylists.activity;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.testcitylists.db.CityDbQuery;
import com.example.testcitylists.R;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;

public class CityActivity extends Activity{
    private static final int LEVEL_PRO=0;
    private static final int LEVEL_CITY=1;
    private static final int LEVEL_COUNTY=2;
    private int currentLevel;

    private ListView lv_cityLists;
    private List dataLists;
    private ArrayAdapterdataAdapter;
    private Context mContext;
    private CityDbQuery cityqb;
    private String selectedPro;
    private String selectedCity;
    private String selectedCounty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_city_activity);
        mContext=this;
        findview();
        bindview();
        queryPro();
    }

    /**
     * loadProvince方法获取省份 列表,将省份列表复制到datalists中;
     * ---同时设置currentLevel为省份级别
     */
    private void queryPro() {
        List mProLists = cityqb.loadProvince();
        if(mProLists!=null){
            dataLists.clear();
            for (String pro:mProLists) {
                //--
                dataLists.add(pro);
                dataAdapter.notifyDataSetChanged();
                currentLevel=LEVEL_PRO;
            }
        }
    }

    /**
     * 设置listview的item点击事件:调用chooseInfo方法
     */
    private void bindview() {
        //点击后执行
        lv_cityLists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int position, long l) {
                chooseInfo(position);
            }
        });
    }


    /**
     * 根据currentLevel的值执行不同的动作:
     * 省:获取到选中省份,并调用queryCity方法--①为了重新设置datalists的数据源②并刷新listview
     * ③ currentLevel也得更改否则没法继续进行
     * @param position 点击item对应的位置,可以获取到你点击了什么
     */
    private void chooseInfo(int position) {

        switch (currentLevel) {
            case LEVEL_PRO:
                //这里我用了datalist而不是mProLists
                selectedPro=dataLists.get(position);
                queryCity(selectedPro);
                break;
            case LEVEL_CITY:
                selectedCity=dataLists.get(position);
                queryCounty(selectedCity);
                break;
            case LEVEL_COUNTY:
                selectedCounty=dataLists.get(position);
                Log.e(TAG, "chooseInfo:"+selectedPro+selectedCity+selectedCounty );
                break;
        }
    }

    private void queryCounty(String selectedCity) {
        List counties = cityqb.loadArea(selectedCity);
        if (counties != null) {
            dataLists.clear();
            for (String county : counties) {
                dataLists.add(county);
                dataAdapter.notifyDataSetChanged();
                currentLevel=LEVEL_COUNTY;
            }
        }
    }

    private void queryCity(String selectedPro) {
        List cities = cityqb.loadCity(selectedPro);
        if(cities.size()>0){
            dataLists.clear();
            for (String city:cities){
                dataLists.add(city);
                dataAdapter.notifyDataSetChanged();
                currentLevel=LEVEL_CITY;
            }
        }
    }

    /**
     * 找到对应控件,并设置dataAdapter的数据源为dataLists;
     * 同时实例化CityDbQuery并调用beginLocalJsonParse方法完成数据查询
     */
    private void findview() {
        lv_cityLists= (ListView) findViewById(R.id.lv_cityList);
        dataLists=new ArrayList<>();

        dataAdapter=new ArrayAdapter(mContext,android.R.layout.simple_list_item_1,dataLists);
        lv_cityLists.setAdapter(dataAdapter);

        cityqb =new CityDbQuery(mContext);
        cityqb.beginLocalJsonParse();
    }
}


Json_城市三级列表实现(两种样式)_第2张图片
Paste_Image.png

你可能感兴趣的:(Json_城市三级列表实现(两种样式))