【问题标题】:Is there any way to dynamically retrieve data to Android spinner from MySQL database?有没有办法从 MySQL 数据库动态检索数据到 Android spinner?
【发布时间】:2014-10-30 05:01:18
【问题描述】:

我在 MySQL 数据库中有两个表:

Country(country_id,country_name)

City(city_id,city_name,country_id)

我想在微调器中检索国家表数据并根据城市表中的城市。我在网上搜索过,但没有找到任何帮助。

我使用 PHP Web 服务作为后端来检索和存储数据库中的数据。我只知道使用ArrayListlist 接口方法(如list.add() 等)在微调器中绑定下拉项。

谁能指导我怎么做?我不需要代码。但是,有人请指导我以哪种方式可以做到这一点?

【问题讨论】:

  • 所以您有两个微调器,一个用于 Country,另一个用于 Cities?而您要做的就是当您从 Country Spinner 中选择国家/地区时,您会自动将相应的城市填充到 Cities Spinner??
  • 我的建议是使用 hashmap 来存储 cityname 和 country_id ..,以便您可以根据需要检索它。
  • @MukeshRana 是的,我有两个微调器,确切地说,我想将相应的城市填充到 Cities Spinner。
  • @Naufal 你的意思是 HashMap 数据结构吗?但是,如果我想在部署应用程序后更改国家或城市的详细信息怎么办。

标签: php android mysql android-spinner android-adapter


【解决方案1】:

因此,根据您的需要,您所要做的就是首先,将国家/地区名称及其对应的 ID 从数据库中的国家/地区表中加载到自定义对象的 ArrayList(包含国家/地区名称和国家/地区 ID)中。从该 ArrayList自定义对象,您必须创建一个国家名称数组并将其绑定到您的国家微调器。当您选择微调器中的国家之一时,您将保存该索引并在自定义对象的 ArrayList 中的相同索引处查找国家 ID。获得 Country Id 后,您只需在 Cities Table 中使用 where 子句进行选择查询,您就可以从那里获得城市名称的 ArrayList 并将该列表填充到您的城市 Spinner 中。

您的自定义对象类将如下所示

public class CountryInfoBean {

    private String countryName = "";
    private String countryId = "";



public String getCountryName() {
    return countryName;
}

public void setCountryName(String countryName) {
    this.countryName = countryName;
}

public String getCountryId() {
    return countryId;
}

public void setCountryId(String countryId) {
    this.countryId = countryId;
}
}

自定义对象的 ArrayList 会是这样的

ArrayList<CountryInfoBean> countriesList=new ArrayList<CountryInfoBean>();

【讨论】:

  • "当您选择微调器中的国家之一时,您将保存该索引并在自定义对象的 ArrayList 中的相同索引处查找国家 ID。"那么,自定义对象的 ArrayList 将具有从国家表解析的 JSON 响应对象?
  • 不不,这不是 JSON 响应。您必须创建一个类 CountryInfoBean,其中您有两个变量 countryName 和 countryId 以及它们的 getter 和 setter,并且您的 arrayList 看起来像这样 ArrayList .因此,当您从数据库中获取 Country Name 和 id 时,您必须创建 CountryInfoBean 对象并设置 countryName 和 countryId 并将该对象放入此 ArrayList
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
  • 2016-03-29
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
相关资源
最近更新 更多