当我将JSON数据设置为Spinner Android时,不会调用Spinner中的OnItemSelectedListener方法

时间:2017-07-28 04:49:38

标签: android json android-spinner

当我为微调器选择静态数据时,它的OnItemSelectedListener方法工作正常,但是当我将JSON数据添加到微调器时,它会填充JSON数据并且不会调用它的OnItemSelectedListener。可能是什么问题呢? 这是我的代码:

class list_Activity extends Activity implements OnItemSelectedListener {

  ProgressDialog progressDialog;
  RequestQueue requestQueue;
  String json_id;
  String json_dept;
  List<String> spinner_dept;
  List<String> categories;
  String selectedCity;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_);
    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading");
    progressDialog.show();

    // Spinner element
    Spinner spinner = (Spinner) findViewById(R.id.spinner3);
    requestQueue= Volley.newRequestQueue(this);

    // Spinner click listener
    spinner.setOnItemSelectedListener(this);

    // Spinner Drop down elements

    spinner_dept = new ArrayList<String>();
    categories = new ArrayList<String>();
    categories.add("Automobile");
    categories.add("Business Services");
    categories.add("Computers");
    categories.add("Education");
    categories.add("Personal");
    categories.add("Travel");

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
      Request.Method.GET,
      "http://192.168.1.104/leave/public/api/department",
      null,
      new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
          progressDialog.dismiss();
          try {
            JSONArray jsonArray = response.getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {
              JSONObject jsonObject = jsonArray.getJSONObject(i);

              String b = jsonArray.getJSONObject(i).getString("department");
              spinner_dept.add(b);

              json_id = jsonObject.getString("identity");
              json_dept = jsonObject.getString("department");

              department deprt = new department();

              deprt.setId(json_id);
              deprt.setDepartment(json_dept);

              // spinner_data.add(deprt);

              // spinner_dept.add(jsonObject.getString("department"));

              //textView.append( id+" "+ first_name + " " + last_name + "\n");
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      },
      new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          Log.d("error", "error from server response");
        }
      });

    requestQueue.add(jsonObjectRequest);

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_dept);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);
  }

  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // On selecting a spinner item
    String item = parent.getItemAtPosition(position).toString();
    // selectedCity = spinner.getSelectedItem().toString();
    if (position != 0) {
      //put your actions here
      String ch =spinner_dept.get(position);

      Toast.makeText(parent.getContext(), "Selected: " + selectedCity, Toast.LENGTH_LONG).show();
    } else {
      // nothing here or toast
      Toast.makeText(parent.getContext(), "Selected: " , Toast.LENGTH_LONG).show();
    }

    // Showing selected spinner item
  }

  public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
  }
}

3 个答案:

答案 0 :(得分:1)

写下你这样的主要活动

    public class HomeFragment extends Fragment {

    Spinner spinmeter;
    ArrayList<Data> categoriesList = new ArrayList<>();
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView= inflater.inflate(R.layout.fragment_home, container, false);

        spinmeter=(Spinner)rootView.findViewById(R.id.spinmeter);
        new GetCategories().execute();
return rootView;
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected Void doInBackground(Void... arg0) {
            ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeServiceCall(
                    "http://meter.digireach.com/demo/app_webservice/spinner.php?did="
                            + did + "", ServiceHandler.GET);

            Log.e("Response: ", "> " + did);

            if (json != "") {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    if (jsonObj != null) {
                        JSONArray data = jsonObj.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject catObj = (JSONObject) data.get(i);
                            Data cat = new Data(catObj.getInt("id"),
                                    catObj.getString("meter_name"));
                            categoriesList.add(cat);
                        }
                    }
                }
                catch (JSONException e) {
                    e.printStackTrace();
                }

            } else
                {
                Log.e("JSON Data", "Didn't receive any data from server!");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
          //  if (pDialog.isShowing())
          //      pDialog.dismiss();
            populateSpinner();
        }

        private void populateSpinner() {
            // TODO Auto-generated method stub
            List<String> lables = new ArrayList<>();

            for (int i = 0; i < categoriesList.size(); i++)
            {
                lables.add(categoriesList.get(i).getUsername());
            }

            // Creating adapter for spinner
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(
                    getActivity(),R.layout.spinner_item, lables);

            // Drop down layout style - list view with radio button
            spinnerAdapter.setDropDownViewResource(R.layout.spinner_item);

            // attaching data adapter to spinner
            spinmeter.setAdapter(spinnerAdapter);

            spinmeter.setOnItemSelectedListener(new OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> parent, View view,
                                           int position, long id) {

                //  meter = spinmeter.getSelectedItem().toString();
                    meter=spinmeter.getSelectedItemPosition()+1;
                    Log.e("Response: ", "> " + meter);

                    if (meter == 1) {
                        new getdata().execute();
                        drawchart();
                        new json1().execute();
                        drawchart1();
                        new json2().execute();
                    }
                    if(meter == 2)
                    {
                        new getdata().execute();
                        drawchart();
                        new json1().execute();
                        drawchart1();
                        new json2().execute();
                    }
                }
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub
                }
            });
        }
    }

还创建java类Data.java

 package com.example.lenovo.meter;

    public class Data {
          private int id;
            private String meter_name;

            public Data(){}

            public Data(int id, String meter_name){
                this.id = id;
                this.meter_name = meter_name;
            }

            public void setId(int id){
                this.id = id;
            }

            public void setUsername(String meter_name){
                this.meter_name = meter_name;
            }

            public int getId(){
                return this.id;
            }

            public String getUsername(){
                return this.meter_name;
            }

    }

创建spinner_item.xml

    <?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="#ffffff"
    android:background="#808080"
    android:padding="10dp"
    />

答案 1 :(得分:1)

添加数据后,您没有刷新适配器。进行以下更改,它将起作用。

// Creating adapter for spinner
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_dept);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://192.168.1.104/leave/public/api/department"
        , null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {

        progressDialog.dismiss();
        try {
            JSONArray jsonArray = response.getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String b = jsonArray.getJSONObject(i).getString("department");
                spinner_dept.add(b);

                json_id = jsonObject.getString("identity");
                json_dept = jsonObject.getString("department");


                department deprt = new department();

                deprt.setId(json_id);
                deprt.setDepartment(json_dept);

               // spinner_data.add(deprt);

               // spinner_dept.add(jsonObject.getString("department"));

                //textView.append( id+" "+ first_name + " " + last_name + "\n");

            }

         //Add this to refresh the spinner adapter
         dataAdapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

        Log.d("error", "error from server response");
    }
}

);


requestQueue.add(jsonObjectRequest);

答案 2 :(得分:0)

IMO你的微调器没有正确引用到SelectedListener所以你可以在onCreate方法之外定义Spinner尝试下面的代码

    ProgressDialog progressDialog;
RequestQueue requestQueue;
String json_id;
String json_dept;
List<String> spinner_dept;
List<String> categories;
String selectedCity;
 Spinner spinner; //here

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_);
 progressDialog= new ProgressDialog(this);
    progressDialog.setMessage("Loading");
    progressDialog.show();

    // Spinner element
    spinner = (Spinner) findViewById(R.id.spinner3);
    requestQueue= Volley.newRequestQueue(this);

    // Spinner click listener
    spinner.setOnItemSelectedListener(this);

    // Spinner Drop down elements

   spinner_dept = new ArrayList<String>();
  categories = new ArrayList<String>();
    categories.add("Automobile");
    categories.add("Business Services");
    categories.add("Computers");
    categories.add("Education");
    categories.add("Personal");
    categories.add("Travel");



     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://192.168.1.104/leave/public/api/department"
            , null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            progressDialog.dismiss();
            try {
                JSONArray jsonArray = response.getJSONArray("data");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String b = jsonArray.getJSONObject(i).getString("department");
                    spinner_dept.add(b);

                    json_id = jsonObject.getString("identity");
                    json_dept = jsonObject.getString("department");


                    department deprt = new department();

                    deprt.setId(json_id);
                    deprt.setDepartment(json_dept);

                   // spinner_data.add(deprt);

                   // spinner_dept.add(jsonObject.getString("department"));

                    //textView.append( id+" "+ first_name + " " + last_name + "\n");

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.d("error", "error from server response");
        }
    }

    );


    requestQueue.add(jsonObjectRequest);

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_dept);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // On selecting a spinner item
    String item = parent.getItemAtPosition(position).toString();
   // selectedCity = spinner.getSelectedItem().toString();
    if (position != 0) {
        //put your actions here
        String ch =spinner_dept.get(position);


        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
    }

    else {
        // nothing here or toast
        Toast.makeText(parent.getContext(), "Selected: " , Toast.LENGTH_LONG).show();
    }


    // Showing selected spinner item

}
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
}