使用JSON数组创建Spinner

时间:2018-01-27 16:33:48

标签: php android json android-studio android-volley

我想在一个微调器中显示我从互联网上下载的JSON数组作为项目。所以我为它创建了一个Activity(SearchActivity)。首先,我的JSON如下:

[ { "Category": "B, A" }, { "Category": "C, B" }, { "Category": "A" }, { "Category": "A, B" }, { "Category": "B" }, { "Category": "C" }, { "Category": "A,C" } ]

这是此PHP代码的结果:

    <?php
    require_once 'include\config.php';
    // connect to database
    $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

    // Check connection
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $content = mysqli_query($con,"SELECT DISTINCT  `Category` FROM `civilarticle` ");

    $output = array();
while($row = mysqli_fetch_array($content)){
     $record = array();
     $record['Category'] = $row['Category'];
     $output[] = $record;
}
    echo json_encode($output);


    //closing connection 
     mysqli_close($con);
?>

这是我的活动:

public class SearchActivity extends Activity {
Spinner spinner;
ArrayList<String> Category;
String url="http://192.168.1.103/android_login_api/search.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    Category=new ArrayList<String>();
    spinner=(Spinner)findViewById(R.id.spinner);
    loadSpinnerData(url);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String category=   spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
            Toast.makeText(getApplicationContext(),category,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            // DO Nothing here
        }
    });

}

private void loadSpinnerData(String url) {
    RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
    StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONArray jsonarray = new JSONArray(response);
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject jsonobject = jsonarray.getJSONObject(i);
                    String Category = jsonobject.getString("Category");
                }
                spinner.setAdapter(new ArrayAdapter<String>(SearchActivity.this, android.R.layout.simple_spinner_dropdown_item, Category));
                //Toast.makeText(SearchActivity.this,response,Toast.LENGTH_SHORT).show();
            }
            catch (JSONException e){e.printStackTrace();}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    requestQueue.add(stringRequest);
}

}

这是我的XML文件:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="15dp"
    android:orientation="vertical"
    tools:context="info.androidhive.customlistviewvolley.SearchActivity">



    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

但是当我运行该程序时。 Spinner上没有任何项目。为什么呢?

2 个答案:

答案 0 :(得分:2)

您需要将收到的项目从回复列表中添加为

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    Category.add(jsonobject.getString("Category"));
}

目前,您只是在局部变量中获取值,该变量未在任何地方使用

答案 1 :(得分:1)

默认情况下,

ArrayAdapter会接受ArrayList

  

ArrayAdapter(Context context,int resource,List objects)
  ArrayAdapter(Context context,int resource,T [] objects)

因此,您需要解析列表中的JSON数据,然后将其传递给适配器。

 try {
        ArrayList<String> catList=new ArrayList<>();
        JSONArray jsonarray = new JSONArray(response);
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject jsonobject = jsonarray.getJSONObject(i);
            catList.add(jsonobject.getString("Category"));
        }
        spinner.setAdapter(new ArrayAdapter<String>(SearchActivity.this,
                android.R.layout.simple_spinner_dropdown_item, catList));
    }catch (Exception e){
        e.printStackTrace();
    }