【问题标题】:dependent android spinners using json data使用 json 数据的依赖 android 微调器
【发布时间】:2016-07-20 03:04:18
【问题描述】:

我浏览了这么多代码并试图找出我做错了什么,但我只是在浪费时间。我无法弄清楚..

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

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

MainActivity.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: %s\n", 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();   
    ?>      

city.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: %s\n", 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 澳大利亚堪培拉

3 澳大利亚悉尼

3 澳大利亚墨尔本

【问题讨论】:

  • 如 json 输出所示,如果我在第一个微调器中单击印度,那么班加罗尔、加尔各答和孟买应显示在第二个微调器中,依此类推..
  • 我们怎么知道例如孟买在印度?您应该在城市 json 中添加国家/地区键,以便您可以根据国家/地区过滤城市。
  • canberre == canberra?
  • @SaNtoRiaN 我已经更新了我的数据库,这样你就可以看到我分配的 ID。如果你只是通过编写一些代码给我一个线索,那么它会对你很有帮助。
  • @MadPhysicist 如果你能在这里帮助我而不是指出我的拼写错误,我将不胜感激

标签: java php android mysql json


【解决方案1】:

假设您的城市位于以下 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);

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2012-04-12
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多