如何根据微调器数据加载listview?

时间:2015-04-26 06:47:24

标签: android listview android-asynctask

这是我的代码。

mainactivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_callplan);
    // lv = getListView();

    city = (Spinner) findViewById(R.id.city_spinner);

    peopleList = new ArrayList<HashMap<String, String>>();

    cityList = new ArrayList<City>();

    city.setOnItemSelectedListener(this);

    new GetCity().execute();

}

private void populateSpinner() {

    // txtCategory.setText("");

    for (int i = 0; i < cityList.size(); i++) {
        cities.add(cityList.get(i).getName());
    }

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

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

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

}

public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub

    // new GetCategories().execute();
    Spinner city1 = (Spinner) parent;

    if (city1.getId() == R.id.city_spinner) {

        cityselected = cities.get(position);

        Toast.makeText(getApplicationContext(), cityselected,
                Toast.LENGTH_LONG).show();

        new GetDoctorsDetails().execute();

    } else {
        Toast.makeText(getApplicationContext(),
                "Please Select City from Dropdown Box", Toast.LENGTH_LONG)
                .show();
    }
}

Asynctask从数据库获取微调数据..

private class GetCity extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(CallplanActivity.this);
        pDialog.setMessage("Fetching cities..");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeServiceCall(URL_CITY,
                ServiceHandler.GET);

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

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                if (jsonObj != null) {
                    JSONArray categories = jsonObj
                            .getJSONArray("doctors_details");

                    for (int i = 0; i < categories.length(); i++) {
                        JSONObject catObj = (JSONObject) categories.get(i);
                        City cat = new City(catObj.getString("city"));
                        cityList.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();
    }

}

这是根据在微调器中选择的值从数据库加载listview项的另一个asynctask。

class GetDoctorsDetails extends AsyncTask<String, String, JSONObject> {

    JSONObject jsonObject;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub

        String city_name = cityselected.toString();
        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
        params1.add(new BasicNameValuePair("city", city_name));

        jsonObject = jParser.makeHttpRequest(URL_DOCTORS, "POST", params1);
        return jsonObject;

    }

    @Override
    protected void onPostExecute(JSONObject json) {
        if (json != null) {
            try {
                doctors_info = json.getJSONArray(TAG_DOCDETAILS);

                for (int i = 0; i < doctors_info.length(); i++) {
                    JSONObject c = doctors_info.getJSONObject(i);

                    String doc_name = c.getString(TAG_DOC_NAME);
                    String qualification = c.getString(TAG_DOC_QUALI);

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_DOC_NAME, doc_name);
                    map.put(TAG_DOC_QUALI, qualification);

                    peopleList.add(map);

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

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    listview = (ListView) findViewById(R.id.listview);
                    // Pass the results into ListViewAdapter.java
                    adapter = new ListViewAdapter(CallplanActivity.this,
                            peopleList);
                    // Set the adapter to the ListView
                    listview.setAdapter(adapter);

                    adapter.notifyDataSetChanged();
                    listview.notify();

                }


            });
        }

        pDialog.dismiss();

    }

}

现在正在加载spinner数据并且listview数据也正确加载但问题是当我从spinner中选择不同的值时,将追加listview中的数据而不是更新。两个微调器数据的值都附加在一个列表视图中。我想在微调器值上显示每个选择的不同数据。

提前感谢。

2 个答案:

答案 0 :(得分:0)

onPostExecute()异步任务的GetDoctorsDetails方法中,在将新结果添加到其中之前,您永远不会清除peopleList数组。整个onPostExecute()方法也在UI线程上执行,因此不需要runOnUiThread

我要做的是先将listview = (ListView) findViewById(R.id.listview);移至onCreate()方法,以避免在每个微调器更改时都搜索它。

您没有使用peopleList本地数组,为什么不直接将项目添加到适配器?因此,使用onPostExecute()启动adapter.clear()。然后使用adapter.add()将所有项目直接添加到适配器(注意 - 根据您实施适配器的方式,您可能需要对add()进行一些小的更改)。最后,只需执行adapter.notifyDataSetChanged()一次即可完成。

同样不需要额外的peopleList代码也会更具可读性。

答案 1 :(得分:0)

这就是我为解决问题而做的事情

public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub

    // new GetCategories().execute();
    Spinner city1 = (Spinner) parent;

    if (city1.getId() == R.id.city_spinner) {

        cityselected = cities.get(position);

        Toast.makeText(getApplicationContext(), cityselected,
                Toast.LENGTH_LONG).show();


        listview = (ListView) findViewById(R.id.listview);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(CallplanActivity.this, peopleList);
        // Set the adapter to the ListView
        listview.setAdapter(adapter);
         adapter.data.clear();
        adapter.notifyDataSetChanged();

        new GetDoctorsDetails().execute();


    } else {
        Toast.makeText(getApplicationContext(),
                "Please Select City from Dropdown Box", Toast.LENGTH_LONG)
                .show();
    }
}