国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 互联网 > android:省市县三级联动(基于json和spring)

android:省市县三级联动(基于json和spring)

来源:程序员人生   发布时间:2014-11-09 10:09:31 阅读次数:3382次

1、请看效果图“:

2、程序的代码:

1、MainActivity.java

package com.loveplusplus.loader.demo.ui;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;


import com.loveplusplus.loader.demo.R;
import com.loveplusplus.loader.demo.util.HttpService;


/**
 * 省市县3级联动
 * 
 * 2014年10月30日 15:22:04
 * 
 * @author YJBo
 * 
 */
public class MainActivity extends Activity {
private static final String HOST_URL = "http://218.241.233.121/yqw";
private static final String PROVINCE_URL = "http://218.241.233.121/yqw/w/c/post?app=join&mdl=web&act=provinces&type=json";
private static final String CITY_URI = HOST_URL
+ "/w/c/post?app=join&mdl=web&type=json&act=citys&col.province=";
private static final String COUNTY_URL = HOST_URL
+ "/w/c/post?app=join&mdl=web&type=json&act=areas&col.city=";
// col.province
private Spinner provinceSpinner;
private Spinner citySpinner;
private Spinner countySpinner;
// 省市县数组
private String[] Province;
private String[] ProvinceCode;
private String json;
// 市---
private String json2;
private String[] City;
private String[] CityCode;
// 县
private String json3;
private String[] Country;
private String[] CountryCode;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获得省的名称
loadProvices();
}


private void loadProvices() {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 初步进入页面,获得所有省分
json = HttpService.postParamAndFileOB(PROVINCE_URL);
mHandler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}


// 市---新
private void loadCitys2(final String provinceCode) {
if (null == provinceCode)
return;
new Thread(new Runnable() {
@Override
public void run() {
try {
// 获得1个省的所有市
json2 = HttpService.postParamAndFileOB(CITY_URI
+ provinceCode);
mHandler.sendEmptyMessage(2);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}


// 县
private void loadCitys3(final String CountryCode) {
if (null == CityCode)
return;
new Thread(new Runnable() {
@Override
public void run() {
try {
// 获得县份数据
json3 = HttpService.postParamAndFileOB(COUNTY_URL
+ CountryCode);
mHandler.sendEmptyMessage(3);
System.out.println("------sheng----麻烦呢-⑶3--");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}


Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
try {
JSONArray array = new JSONArray(json);
Province = new String[array.length()];
ProvinceCode = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject obj = (JSONObject) array.get(i);
Province[i] = obj.getString("name");
ProvinceCode[i] = obj.getString("code");
}
provinceSpinner = (Spinner) findViewById(R.id.spinner_province);
// 初始化下拉列表加载数据适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item, Province);
// 设置下拉列表的样式,下为设置为简单样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// 将数据加载进下拉列表当中
provinceSpinner.setAdapter(adapter);
// 添加事件Spinner事件监听,当点击下拉列表中的某1选项以后触发该事件
provinceSpinner
.setOnItemSelectedListener(new SpinnerSelectedListener());
// 设置默许值
provinceSpinner.setVisibility(View.VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 市
case 2:
try {
JSONArray array = new JSONArray(json2);
City = new String[array.length()];
CityCode = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject obj = (JSONObject) array.get(i);
City[i] = obj.getString("name");
CityCode[i] = obj.getString("code");
}
citySpinner = (Spinner) findViewById(R.id.spinner_city);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item, City);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(adapter);
citySpinner.setOnItemSelectedListener(new SpinLisSHi());
citySpinner.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
break;
// 县
case 3:
try {
JSONArray array = new JSONArray(json3);
Country = new String[array.length()];
CountryCode = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject obj = (JSONObject) array.get(i);
Country[i] = obj.getString("name");
CountryCode[i] = obj.getString("code");
}
countySpinner = (Spinner) findViewById(R.id.spinner_county);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item, Country);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countySpinner.setAdapter(adapter);
countySpinner.setOnItemSelectedListener(new SpinLisXian());
countySpinner.setVisibility(View.VISIBLE);


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


default:
break;
}
super.handleMessage(msg);
}
};


class SpinnerSelectedListener implements OnItemSelectedListener {


public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(MainActivity.this, Province[arg2], 3000).show();
// 下载市的名称
loadCitys2(ProvinceCode[arg2]);
}


public void onNothingSelected(AdapterView<?> arg0) {
}
}


// 市
class SpinLisSHi implements OnItemSelectedListener {


public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(MainActivity.this, City[arg2], 3000).show();
// 下载县的名称
loadCitys3(CityCode[arg2]);
}


public void onNothingSelected(AdapterView<?> arg0) {
}
}


// 县
class SpinLisXian implements OnItemSelectedListener {


public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(MainActivity.this,
Country[arg2] + CountryCode[arg2], 3000).show();
}


public void onNothingSelected(AdapterView<?> arg0) {
}
}
}


2、httpService.java

package com.loveplusplus.loader.demo.util;


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


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


/**
 * 2014年7月20日 16:26:40 这里是解析url的;
 * 
 * @author YJBo
 */
public class HttpService {


public static void main(String[] args) {
}



public static String postParamAndFileOB(String url) {
// http地址
String httpUrl = url;
System.out.println("此时的OB地址httpUrl++==" + httpUrl);
System.out
.println("--------------http://www.wfuyu.com/db/正在链接中・・・・----------------------------");
try {
// HttpGet连接对象
HttpPost httpRequest = new HttpPost(httpUrl);
System.out.println("==wo走到这里了 20===");


System.out.println("==wo走到这里了 21===");
// 使用NameValuePair来保存要传递的Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "UTF⑻");
// 要求httpRequest
httpRequest.setEntity(httpentity);
// 获得HttpClient对象
HttpClient httpclient = new DefaultHttpClient();
// 要求HttpClient,获得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
System.out.println("==wo走到这里了 23===");
// 要求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 获得返回的字符串
System.out.println("==wo走到这里了 24===");
String strResultOB = EntityUtils.toString(httpResponse
.getEntity());
// .getEntity();
System.out.println("==wo走到这里了 22===" + strResultOB);
return strResultOB;
} else {
System.out.println("数据要求失败====");
}


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}


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:orientation="vertical"
    tools:context=".ui.MainActivity" >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical" >


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:text="@string/select_province"
            android:textSize="20sp" />


        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/separator_line"
            android:contentDescription="@string/app_name" />


        <Spinner
            android:id="@+id/spinner_province"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"/>
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical" >


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:text="@string/select_city"
            android:textSize="20sp" />


        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/separator_line"
            android:contentDescription="@string/app_name" />


        <Spinner
            android:id="@+id/spinner_city"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical" >


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:text="@string/select_county"
            android:textSize="20sp" />


        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/separator_line"
            android:contentDescription="@string/app_name" />


        <Spinner
            android:id="@+id/spinner_county"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />
    </LinearLayout>


</LinearLayout>

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生