将组和标题动态添加到可扩展列表视图

时间:2014-08-29 14:48:35

标签: java android json expandablelistview

我有数据作为JSON数组进入,我正在解析它。这是一个例子:

[{"Tag":"Amusement Parks","Category":"Attractions"},{"Tag":"Restaurant","Category":"Food"}, etc]

我想做的是制作每个"类别" ListView中的标题和每个"标记"那个标题的孩子。现在我正在努力编写Header并添加像这样的标签:

    listDataHeader.add("Attractions");
    listDataHeader.add("Food");
    listDataHeader.add("Lodging");

            ...

            JSONArray jArray = new JSONArray(result);
            Log.d("Array Length: ", Integer.toString(jArray.length()));

            for (int i = 0; i < jArray.length(); i++) {
                final JSONObject json = jArray.getJSONObject(i);

                if (json.getString("Category").equals("Attractions")) {
                    tempAttractions.add(json.getString("Tag"));
                }
                if (json.getString("Category").equals("Food")) {
                    tempFood.add(json.getString("Tag"));
                }
                if (json.getString("Category").equals("Lodging")) {
                    tempLodging.add(json.getString("Tag"));
                }
            }
    }

    protected void onPostExecute(Void... params) {

        listDataChild.put(listDataHeader.get(0), tempAttractions);
        listDataChild.put(listDataHeader.get(1), tempFood);
        listDataChild.put(listDataHeader.get(2), tempLodging);

但是我不想对类别进行硬编码,而是想从JSON数据中动态添加类别。

所以基本上就是这样......

//obviously pseudo code...
if (json.getString("Category") exists as a header already) {
    add json.getString("Tag") as a child under that group
//or if it doesn't exist
} else {
    add a header header and add json.getString("Tag") as a child under that group
}

我认为这更像是一个概念问题,我似乎无法抓住一种方法来完成这项工作。有任何想法吗?谢谢!

完整代码

公共类CategorySelect扩展了BaseActivity {

ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;

private String[] navMenuTitles;
private TypedArray navMenuIcons;

List<String> listAttractions;
List<String> listFood;
List<String> listLodging;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category_select);

    // initialize Nav Drawer
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);
    set(navMenuTitles, navMenuIcons);

    progress = new ProgressDialog(this);
    progress.setMessage("Loading...Please Wait");
    progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progress.setIndeterminate(true);

    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.lvExp);

    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader,
            listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);
}

private void prepareListData() {
    listDataHeader = new ArrayList<String>();
    listDataChild = new HashMap<String, List<String>>();

    // Adding child data
    listDataHeader.add("Attractions");
    listDataHeader.add("Food");
    listDataHeader.add("Lodging");

    listAttractions = new ArrayList<String>();
    listFood = new ArrayList<String>();
    listLodging = new ArrayList<String>();

    new FillCategories().execute();
}

private class FillCategories extends
        AsyncTask<Integer, Void, Void> {
    List<String> tempAttractions = new ArrayList<String>();
    List<String> tempFood = new ArrayList<String>();
    List<String> tempLodging = new ArrayList<String>();

    @Override
    protected ArrayList<Location> doInBackground(Integer... params) {

        String result = "";
        InputStream isr = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "");

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            String action = "nav";

            nameValuePairs.add(new BasicNameValuePair("action", action));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            isr.close();

            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error  converting result " + e.toString());
        }

        // parse json data
        try {
            JSONArray jArray = new JSONArray(result);
            Log.d("Array Length: ", Integer.toString(jArray.length()));

            for (int i = 0; i < jArray.length(); i++) {
                final JSONObject json = jArray.getJSONObject(i);

                //Log.d("Text", json.getString("Txt"));

                if (json.getString("Cat").equals("Attractions")) {
                    tempAttractions.add(json.getString("Txt"));
                    if (json.getString("Tag").equals(null)) {
                        tempAttractionsTags.add(json.getString("Txt"));
                    } else {
                        tempAttractionsTags.add(json.getString("Tag"));
                    }
                }
                if (json.getString("Cat").equals("Food")) {
                    tempFood.add(json.getString("Txt"));
                    if (json.getString("Tag").equals(null)) {
                        tempFoodTags.add(json.getString("Txt"));
                    } else {
                        tempFoodTags.add(json.getString("Tag"));
                    }
                }
                if (json.getString("Cat").equals("Lodging")) {
                    tempLodging.add(json.getString("Txt"));
                    if (json.getString("Tag").equals("")) {
                        tempLodgingTags.add(json.getString("Txt"));
                        Log.d("Tag", "Is Null");
                    } else {
                        tempLodgingTags.add(json.getString("Tag"));
                        Log.d("Tag Not Null", json.getString("Tag"));
                    }
                }
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    protected void onPostExecute(Void... params) {

        listDataChild.put(listDataHeader.get(0), tempAttractions);
        listDataChild.put(listDataHeader.get(1), tempFood);
        listDataChild.put(listDataHeader.get(2), tempLodging);

    }
}
}

2 个答案:

答案 0 :(得分:1)

你可以做这样的事情

            for (int i = 0; i < jArray.length(); i++) {
            final JSONObject json = jArray.getJSONObject(i);

            if (listDataChild.get(json.getString("Category")) == null) {
               tempList = new ArrayList<String>();
               tempList.add(json.getString("Tag"));
               listDataChild.put(json.getString("Category"), tempList );
            }else{
               tempList = listDataChild.get(json.getString("Category"));
               tempList.add(json.getString("Tag"));
               listDataChild.put(json.getString("Category"), tempList );
           }

答案 1 :(得分:0)

您可以使用此库:library,它非常简单且非常高效