如何将数据库值绑定到Android代码中的Spinner下拉列表?

时间:2014-08-10 17:45:47

标签: android mysql

我使用以下简单代码从mysql数据库表中获取值。

  

我不知道如何将这些值绑定到Spinner下拉列表

 public String select() throws JSONException
{

            //ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        //nameValuePairs.add(new BasicNameValuePair("id",id));

            try
            {
            HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.mydemo.com/select.php");
                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }
            catch(Exception e)
        {

        }     

            try
            {
                BufferedReader reader = new BufferedReader
                    (new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null)
            {
                    sb.append(line + "\n");
                }
                    is.close();
                    result = sb.toString();

        }
            catch(Exception e)
            {
                }     


                JSONObject json_data = new JSONObject(result);
                return (json_data.getString("name"));



}

1 个答案:

答案 0 :(得分:2)

或者:

  • 将数据从JSONObject复制到您在ArrayList中打包的POJO,然后使用ArrayAdapter

  • 使用可以为您生成ArrayList的更好的JSON解析器(例如,Google的GSON),然后使用ArrayAdapter

  • Retrofit(和GSON)替换上面的所有代码,为您检索并生成ArrayList,然后使用ArrayAdapter

  • 创建自己的BaseAdapter子类,用于包裹JSONObject,以及ArrayAdapter如何适应数组和CursorAdapter适应{{1} }}

还有其他可能性,尽管这些可能会让你开始。

This sample project演示了Retrofit + GSON方法,从Stack Exchange API中提取数据并将其放入Cursors。使用ListView只需重新配置Spinner并使用适当的布局。

相关问题