【问题标题】:how to load listview depending upon spinner data?如何根据微调器数据加载列表视图?
【发布时间】:2015-04-26 06:47:23
【问题描述】:

这是我的代码。

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();
    }
}

从数据库中获取微调器数据的异步任务..

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();
    }

}

这是另一个异步任务,用于根据微调器中选择的值从数据库中加载列表视图项。

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();

    }

}

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

提前致谢。

【问题讨论】:

  • 我解决了我的问题。经过太多搜索,这里提到了另一个问题。我所做的只是从 UI 线程中删除了我的适配器并将其放在 onItemSelected () 方法中。这解决了我的问题。
  • 这篇文章帮助了我..stackoverflow.com/questions/12973121/…

标签: android listview android-asynctask


【解决方案1】:

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

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

为什么不直接向适配器添加项目而不是使用peopleList 本地数组?所以以adapter.clear() 开头onPostExecute()。比使用 adapter.add() 直接将所有项目添加到适配器(注意 - 根据您实现适配器的方式,您可能需要对 add() 做一些小的更改)。最后只需执行一次adapter.notifyDataSetChanged() 即可。

同时消除额外的peopleList,您的代码将更具可读性。

【讨论】:

    【解决方案2】:

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

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多