gpt4 book ai didi

java - 使用 json 数据的依赖 android spinner

转载 作者:行者123 更新时间:2023-11-29 21:11:23 25 4
gpt4 key购买 nike

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

我正在开发一个 Android 应用程序,需要在一项 Activity 中放置 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 用于获取国家和城市的值

国家.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();
?>

城市.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 数组中

[{"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);

希望对你有帮助

关于java - 使用 json 数据的依赖 android spinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com