Android学习之省份城市县区选择+向上一级活动返回数据

json数据使用的是郭霖大神的json数据:http://guolin.tech/api/china/

连网权限

<uses-permission android:name="android.permission.INTERNET" />
添加对OkHttp库的依赖:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.6.0'
源码下载地址:http://download.csdn.net/download/kh971024/10043153

实体类Area,省份、城市和县区共用

public class Area {
    private String id;
    private String name;

    public Area(String id,String name){
        this.id = id;
        this.name = name;
    }

    public String getId(){
        return id;
    }

    public String getName() {
        return name;
    }
}
MyAdapter类,是spinner数据的适配器,省份、城市和县区共用

public class MyAdapter extends BaseAdapter {
    private List<Area> mList;
    private Context mContext;

    public MyAdapter(Context pContext, List<Area> pList){
        this.mContext = pContext;
        this.mList = pList;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int i) {
        return mList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        LayoutInflater _LayoutInflater= LayoutInflater.from(mContext);
        view = _LayoutInflater.inflate(R.layout.item,null);
        TextView name = (TextView) view.findViewById(R.id.name);
        name.setText(mList.get(i).getName());
        return view;
    }
}
MainActivity,选择省份城市县区等数据后会向这个活动返回数据显示

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button action;
    private int RequestCode = 1;
    private TextView province_name,city_name,county_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        action = (Button) findViewById(R.id.choice);
        action.setOnClickListener(this);

        province_name = (TextView) findViewById(R.id.province_name);
        city_name = (TextView) findViewById(R.id.city_name);
        county_name = (TextView) findViewById(R.id.county_name);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.choice:{
                Intent intent = new Intent(this,ChoiceActivity.class);
                startActivityForResult(intent,RequestCode);
            }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==2){
            province_name.setText(data.getStringExtra("province"));
            city_name.setText(data.getStringExtra("city"));
            county_name.setText(data.getStringExtra("county"));
        }
    }
}
MainActivity对应的布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.konghao.spinner.MainActivity">

    <LinearLayout
        android:id="@+id/layout_1"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:orientation="vertical"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/province_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="省份"
            android:textSize="24dp" />

        <TextView
            android:id="@+id/city_name"
            android:text="城市"
            android:textSize="24dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/county_name"
            android:text="县/区"
            android:textSize="24dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <Button
        android:id="@+id/choice"
        android:text="选择"
        android:textSize="20dp"
        android:layout_marginTop="32dp"
        android:layout_marginRight="20dp"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/layout_1"
        android:layout_alignLeft="@+id/layout_1"
        android:layout_alignStart="@+id/layout_1" />

</RelativeLayout>
HttpUtil类,发送获取json数据的请求

public class HttpUtil {
    public static void sendHttpRequest(String address, Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
    }
}
ChoiceActivity,选择省份、城市和县区的活动

public class ChoiceActivity extends Activity implements View.OnClickListener{

    private Spinner province_spinner,city_spinner,county_spinner;
    private List<Area> provinces = new ArrayList<Area>();//省份列表
    private List<Area> cities = new ArrayList<Area>();//城市列表
    private List<Area> counties = new ArrayList<Area>();//县区列表
    private MyAdapter province_adapter;//省份数据适配器
    private MyAdapter city_adapter;//城市数据适配器
    private MyAdapter county_adapter;//县区数据适配器
    private String address;
    private String province_name,city_name,county_name;
    private String province_id,city_id,county_id;
    private Button return_button;
    private int ResultCode = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice);

        province_spinner = (Spinner) findViewById(R.id.province_spinner);
        city_spinner = (Spinner) findViewById(R.id.city_spinner);
        county_spinner = (Spinner) findViewById(R.id.county_spinner);
        return_button = (Button) findViewById(R.id.ok);
        return_button.setOnClickListener(this);

        //省份选择
        province_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Area area = provinces.get(i);
                province_id = area.getId();
                province_name = area.getName();
                initCityData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //城市选择
        city_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Area area = cities.get(i);
                city_id = area.getId();
                city_name = area.getName();
                initCountyData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //县区选择
        county_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Area area = counties.get(i);
                county_id = area.getId();
                county_name = area.getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        initProvinceData();

    }

    //用来设置适配器
    Handler myhandle = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:{
                    //实例化适配器
                    province_adapter = new MyAdapter(ChoiceActivity.this,provinces);
                    province_spinner.setAdapter(province_adapter);
                }
                    break;
                case 2:{
                    city_adapter = new MyAdapter(ChoiceActivity.this,cities);
                    city_spinner.setAdapter(city_adapter);
                }
                    break;
                case 3:{
                    county_adapter = new MyAdapter(ChoiceActivity.this,counties);
                    county_spinner.setAdapter(county_adapter);
                }
                    break;
            }
        }
    };

    public void initProvinceData(){
        address = "http://guolin.tech/api/china/";

        HttpUtil.sendHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                DealProData(responsedata);
            }
        });
    }

    public void DealProData(String data){
        try{
            int i;
            JSONArray jsonArray = new JSONArray(data);
            for(i = 0;i < jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");

                Area area = new Area(id,name);
                provinces.add(area);
            }
            if(i==jsonArray.length()){
                myhandle.sendEmptyMessage(1);
            }

        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    public void initCityData(){
        address = "http://guolin.tech/api/china/" + province_id;

        HttpUtil.sendHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                DealCityData(responsedata);
            }
        });
    }

    public void DealCityData(String data){
        try{
            int i;
            cities.clear();//请出之前的城市列表
            JSONArray jsonArray = new JSONArray(data);
            for(i = 0;i < jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");

                Area area = new Area(id,name);
                cities.add(area);
            }
            if(i==jsonArray.length()){
                myhandle.sendEmptyMessage(2);
            }

        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    public void initCountyData(){
        address = "http://guolin.tech/api/china/" + province_id +"/"+ city_id;

        HttpUtil.sendHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                DealCouData(responsedata);
            }
        });
    }

    public void DealCouData(String data){
        try{
            int i;
            counties.clear();//请出之前的城市列表
            JSONArray jsonArray = new JSONArray(data);
            for(i = 0;i < jsonArray.length();i++){
                Log.d("孔昊","1");
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");

                Area area = new Area(id,name);
                counties.add(area);
            }
            if(i==jsonArray.length()){
                myhandle.sendEmptyMessage(3);
            }

        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ok:{
                Intent intent = new Intent();
                intent.putExtra("province",province_name);
                intent.putExtra("city",city_name);
                intent.putExtra("county",county_name);
                setResult(ResultCode,intent);//向上一级发送数据
                finish();
            }
                break;
        }
    }
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值