java - 将组和标题动态添加到可扩展 ListView

标签 java android json expandablelistview

我有一个 JSON 数组形式的数据,我正在解析它。这是一个例子:

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

我想要做的是将每个“类别”设置为 ListView 中的标题,并将每个“标签”设置为该标题的子项。现在我正在对标题进行硬编码并添加标签,如下所示:

    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
}

我认为这更多的是一个概念问题,我似乎无法掌握完成此任务的方法。有任何想法吗?谢谢!

完整代码

公共(public)类 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);

    }
}
}

最佳答案

你可以做这样的事情

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

关于java - 将组和标题动态添加到可扩展 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570758/

相关文章:

android - 传感器_延迟_游戏 : how much is it?

javascript - 在 Polymer 元素之间传递数组和/或对象数据

java - boolean 值总是返回 true

java - 使用eclipse在tomcat上部署后找不到页面

java - 全屏操作栏问题

java - 具有值列表的映射的现有 Java 实现?

android - 有没有办法创建一个有角度的 ListView/RecycleView?

php - 如何使用其键将数组分组为子数组?

java - 如何从 libgdx 中的文件系统读取特殊字符

java - 创建 Dom4J SaxReader 对象池有什么值(value)吗?