使用json数据的依赖android微调器



我已经读了很多代码,试图找出我做错了什么,但我只是在浪费时间。我想不通。。

我正在开发一个android应用程序,需要在一个活动中放置2个微调器。第二个微调器将根据第一个微调器上选择的条目进行填充,所有数据都将从json中获取。

我有一个mysql表,其中有两列,即国家和城市。我已经分别在两个微调器中获得了国家和城市的数据,现在当用户选择一个国家名称时,该特定国家的城市应该列在第二个微调器。

主要活动.java

public class LinearLayout extends Activity implements
     View.OnClickListener{
ArrayList<String> listItems=new ArrayList<>();
ArrayList<String> listItems1=new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapter1;
Button submit;
Spinner s1,s2;
String text="";
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.linear_layout);
    submit=(Button)findViewById(R.id.submit);
    submit.setOnClickListener(this);
    s1 = (Spinner)findViewById(R.id.spinner1);
    adapter=new ArrayAdapter<>(this,R.layout.spinner_layout,R.id.txt,listItems);
    s1.setAdapter(adapter);
    s2 = (Spinner)findViewById(R.id.spinner2);
    adapter1=new ArrayAdapter<>(this,R.layout.spinner_layout,R.id.txt,listItems1);
    s2.setAdapter(adapter1);
       }
public void onStart(){
    super.onStart();
    BackTask bt=new BackTask();
    bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
    ArrayList<String> list;
    ArrayList<String> list1;
    protected void onPreExecute(){
        super.onPreExecute();
        list=new ArrayList<>();
        list1=new ArrayList<>();
    }
    protected Void doInBackground(Void...params){
        InputStream is=null;
        String result="";
        String result1="";
        InputStream is1=null;
        try{
            HttpClient httpclient=new DefaultHttpClient();
            HttpPost httppost= new HttpPost("http://192.168.3.2/countries.php");
            HttpResponse response=httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            // Get our response as a String.
            is = entity.getContent();
            HttpClient httpclient1=new DefaultHttpClient();
            HttpPost httppost1= new HttpPost("http://192.168.3.2/cities.php");
            HttpResponse response1=httpclient1.execute(httppost1);
            HttpEntity entity1 = response1.getEntity();
            // Get our response as a String.
            is1 = entity1.getContent();
        }catch(IOException e){
            e.printStackTrace();
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
            BufferedReader reader1 = new BufferedReader(new InputStreamReader(is1,"utf-8"));
            String line = null;
            String line1= null;
            while ((line = reader.readLine()) != null) {
                result+=line;
            }
            while ((line1 = reader1.readLine()) != null) {
                result1+=line1;
            }
            is.close();
            //result=sb.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        // parse json data
        try{
            JSONArray jArray =new JSONArray(result);
            //MANUFACTURER = new String[jArray.length()];
            for(int i=0;i<jArray.length();i++) {
                JSONObject jsonObject = jArray.getJSONObject(i);
                // add interviewee name to arraylist
                list.add(jsonObject.getString("country"));
            }
                JSONArray jArray1 =new JSONArray(result1);
                //MANUFACTURER = new String[jArray.length()];
                for(int j=0;j<jArray.length();j++){
                    JSONObject jsonObject1=jArray1.getJSONObject(j);
                    // add interviewee name to arraylist
                    list1.add(jsonObject1.getString("city"));
            }
            //spinner_fn();
        }
        catch(JSONException e){
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(Void result){
        listItems.addAll(list);
        adapter.notifyDataSetChanged();
        listItems1.addAll(list1);
        adapter1.notifyDataSetChanged();
        //adapter1.notifyDataSetChanged();
    }
}

这里我有2个php用于获取国家和城市的值

countries.php

<?php
    $DB_USER='root'; 
    $DB_PASS='mysql'; 
    $DB_HOST='localhost';
    $DB_NAME='xxxx';
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
    /* check connection */
    if (mysqli_connect_errno()) {
    printf("Connect failed: %sn", mysqli_connect_error());
    exit();
    }       
        $mysqli->query("SET NAMES 'utf8'");
    $sql="SELECT DISTINCT country from ssss";
    $result=$mysqli->query($sql);
    while($e=mysqli_fetch_assoc($result)){
    $output[]=$e; 
    }
    print(json_encode($output));
    $mysqli->close();   
    ?>      

cities.php

<?php
    $DB_USER='root'; 
    $DB_PASS='mysql'; 
    $DB_HOST='localhost';
    $DB_NAME='xxxx';
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
    /* check connection */
    if (mysqli_connect_errno()) {
    printf("Connect failed: %sn", mysqli_connect_error());
    exit();
    }       
    $mysqli->query("SET NAMES 'utf8'");
    $sql1="select city from ssss";
    $result1=$mysqli->query($sql1);
    while($f=mysqli_fetch_assoc($result1)){
    $output1[]=$f; 
    }
    print (json_encode($output1));
    $mysqli->close();   
    ?>      

这是我的json输出

[{"country":"india"},{"country":"england"},{"country":"australia"}]
[{"city":"bangalore"},{"city":"kolkata"},{"city":"mumbai"},{"city":"london"},{"city":"manchester"},{"city":"southampton"},{"city":"canberra"},{"city":"sydney"},{"city":"melbourne"}]

现在我知道我必须添加一个onitemclicklistener,但我不知道如何在第二个旋转中获得依赖城市

这是我的数据库

ID国家/城市

1印度班加罗尔

1印度加尔各答

1印度孟买

2英格兰伦敦

2英格兰曼彻斯特

2英格兰南安普顿

3澳大利亚canberra

3澳大利亚悉尼

3澳大利亚墨尔本

假设您的城市位于以下json数组上

[{"country":"india", "city":"city1"},{"country":"england", "city":"city2"},{"country":"australia", "city":"city3"}]

尝试以下

// map to keep each country and its cities
final HashMap<String, ArrayList<String>> data = new HashMap<>();
// add your json array
JSONArray array;
try {
    array = new JSONArray("");
} catch (JSONException e) {
    e.printStackTrace();
    return;
}
try {
    for (int i = 0; i < array.length(); i++) {
        JSONObject item = array.getJSONObject(i);
        String country = item.getString("country");
        // get the country from the map according to the country in json
        ArrayList<String> dataList = data.get(country);
        // if the list is null "the map doesn't have the list", create new one and add it to the map
        // else add the city to the country list
        if (dataList == null) {
            dataList = new ArrayList<>();
            data.put(country, dataList);
        }
        dataList.add(item.getString("city"));
    }
} catch (JSONException e) {
    e.printStackTrace();
}
final ArrayList<String> citiesList = new ArrayList<>();
final ArrayAdapter<String> citiesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, citiesList);
Spinner countriesSpinner = (Spinner) findViewById(R.id.spCountries);
// create the countries list to add it to the countries spinner
final ArrayList<String> countriesList = new ArrayList<>();
countriesList.add("india");
countriesList.add("england");
countriesList.add("australia");
countriesSpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, countriesList));
countriesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // get the selected country from spinner
        String selectedCountry = countriesList.get(position);
        // get the cities in the selected country
        ArrayList<String> cities = data.get(selectedCountry);
        // clear the list then add new cities
        citiesList.clear();
        for (String city : cities)
            citiesList.add(city);
        citiesAdapter.notifyDataSetChanged();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});
Spinner citiesSpinner = (Spinner) findViewById(R.id.spCities);
citiesSpinner.setAdapter(citiesAdapter);

希望它能帮助

相关内容

最新更新