【问题标题】:create Views from HashMap inside ArrayList从 ArrayList 中的 HashMap 创建视图
【发布时间】:2013-05-30 06:06:03
【问题描述】:

这是一个我似乎无法解决的逻辑问题,但我认为我已经接近了。我从JSON 响应中获取值并将它们存储在HashMap 中,然后将HashMap 添加到ArrayList

doInBackground

protected String doInBackground(String... args) {

            // getting JSON string from URL
            companyName = cn.getText().toString();
            projectName = pn.getText().toString();
            String componentName = (String) ab.getSelectedTab().getText();

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("company", companyName));
            nameValuePairs.add(new BasicNameValuePair("project", projectName));
            nameValuePairs.add(new BasicNameValuePair("component",
                    componentName));

            JSONObject json = jParser.makeHttpRequest(url, "POST",
                    nameValuePairs);

            // Check your log cat for JSON response
            Log.d("All Questions: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    Log.v("RESPONSE", "Success!");
                    // products found: getting Array of Questions
                    questions = json.getJSONArray(TAG_QUESTIONS);

                    // looping through All Questions
                    for (int i = 0; i < questions.length(); i++) {

                        JSONObject c = questions.getJSONObject(i);

                        // Storing each JSON item in variable
                        String name = c.getString(TAG_NAME);
                        String field = c.getString(TAG_FIELD);
                        String value = c.getString(TAG_VALUE);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_NAME, name);
                        map.put(TAG_FIELD, field);
                        map.put(TAG_VALUE, value);
                        for (String key: map.keySet()) {
                            System.out.println("key : " + key);
                            System.out.println("value : " + map.get(key));
                        }
                        infoList.add(map);
                    }

                } else {
                    // no products found
                    Log.v("ERROR", "No JSON for you!");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

现在上面的for loop从我的JSON打印以下内容

06-03 19:35:29.928: I/System.out(9691): key : option_value
06-03 19:35:29.928: I/System.out(9691): value : 
06-03 19:35:29.928: I/System.out(9691): key : field_type
06-03 19:35:29.928: I/System.out(9691): value : Text Field
06-03 19:35:29.928: I/System.out(9691): key : display_name
06-03 19:35:29.928: I/System.out(9691): value : Store #
06-03 19:35:29.928: I/System.out(9691): key : option_value
06-03 19:35:29.928: I/System.out(9691): value : 
06-03 19:35:29.928: I/System.out(9691): key : field_type
06-03 19:35:29.928: I/System.out(9691): value : Text Field
06-03 19:35:29.928: I/System.out(9691): key : display_name
06-03 19:35:29.938: I/System.out(9691): value : Address
06-03 19:35:29.938: I/System.out(9691): key : option_value
06-03 19:35:29.938: I/System.out(9691): value : Education
06-03 19:35:29.938: I/System.out(9691): Health
06-03 19:35:29.938: I/System.out(9691): Computers
06-03 19:35:29.938: I/System.out(9691): Food
06-03 19:35:29.938: I/System.out(9691): Retail
06-03 19:35:29.938: I/System.out(9691): Other
06-03 19:35:29.938: I/System.out(9691): key : field_type
06-03 19:35:29.938: I/System.out(9691): value : Drop Down Menu
06-03 19:35:29.938: I/System.out(9691): key : display_name
06-03 19:35:29.938: I/System.out(9691): value : Type of Business
06-03 19:35:29.938: I/System.out(9691): key : option_value
06-03 19:35:29.938: I/System.out(9691): value : Yes
06-03 19:35:29.938: I/System.out(9691): No
06-03 19:35:29.938: I/System.out(9691): key : field_type
06-03 19:35:29.938: I/System.out(9691): value : Radio
06-03 19:35:29.938: I/System.out(9691): key : display_name
06-03 19:35:29.938: I/System.out(9691): value : Is this business good?
06-03 19:35:29.938: I/System.out(9691): key : option_value
06-03 19:35:29.938: I/System.out(9691): value : Yes
06-03 19:35:29.938: I/System.out(9691): No
06-03 19:35:29.938: I/System.out(9691): key : field_type
06-03 19:35:29.938: I/System.out(9691): value : Check Box
06-03 19:35:29.938: I/System.out(9691): key : display_name
06-03 19:35:29.938: I/System.out(9691): value : Are they nice people?

JSON

{
    "questions": [
        {
            "display_name": "Store #",
            "field_type": "Text Field",
            "option_value": ""
        },
        {
            "display_name": "Address",
            "field_type": "Text Field",
            "option_value": ""
        },
        {
            "display_name": "Type of Business",
            "field_type": "Drop Down Menu",
            "option_value": "Education\r\nHealth\r\nComputers\r\nFood\r\nRetail\r\nOther"
        },
        {
            "display_name": "Is this business good?",
            "field_type": "Radio",
            "option_value": "Yes\r\nNo"
        },
        {
            "display_name": "Are they nice people?",
            "field_type": "Check Box",
            "option_value": "Yes\r\nNo"
        }
    ],
    "success": 1
}

现在在onPostExecute() 中,我需要遍历名为“infoList”的ArrayList,然后获取HashMap 值。基于该信息,我需要创建Views。所以我的代码应该是这样的,但我做错了。

protected void onPostExecute(String string) {
    // dismiss the dialog
    pDialog.dismiss();  
    for (int i = 0; i < infoList.size(); i++) {
        // get HashMap, how? i.toString()?
        for (String key: map.keySet()) {
        if (map.get(key).equals("Radio")) {
                //create RadioButtons, setTexts to option_value values         
            } else if (map.get(key).equals("Text Field")) {
                //create EditText
            } else if (map.get(key).equals("Check Box")) {
                //create CheckBox's, setTexts to option_value values
            } else if (map.get(key).equals("Drop Down Menu")) {
                //create Spinner, place option_value values into array and populate
            }
         }
    }

那么我是否让这件事变得比需要的更难?我觉得他们必须是一个更简单的方法。如果不是,我将非常感谢编写此for loop 的一些帮助。

编辑以响应 cmets

我希望这样可以在 fragment 中填充一个看起来像这样的布局

Store # ------------------ <EditText>
Address ------------------ <EditText>
Is this business good? --- <RadioButton>

等等。RadioButtonCheckbox 的文本将由 optional_values 设置

完成后,我会将其发送回我最初从中获取此信息的数据库。

【问题讨论】:

  • 想展示一些 JSON 数据?当某些 JSON 库已经拥有您需要的东西时,您似乎不需要所有这些机器......(个人意见:org.json 在您想要导航时是一个非常糟糕的库)
  • @fge 发布了 JSON,如果有什么可以帮我做的,请告诉我
  • 实际上是的:您期望从此类 JSON 输入中得到什么输出?之后你会怎么做?
  • infoList.get(i) 是获取地图的方法
  • @i_me_mine 查看部分答案;你真的应该使用杰克逊。

标签: java android json for-loop arraylist


【解决方案1】:

与使用不合适的库相比,您自己更难做到。

使用Jackson,您将更轻松地做您想做的事。首先,从输入源中获取JsonNode,这通常通过ObjectMapper 完成:

// "mapper" is an already initialized ObjectMapper
final JsonNode response = mapper.readTree(yourURL); // catch, treat IOException

现在,阅读success

if (response.get("success").intValue() != 1 )
    // deal with failure

成功了吗?处理所有值:

for (final JsonNode question: response.get("questions"))
    // do something with "question", which is an element of the "questions" array

请参阅JsonNode 的文档。在 Java 中没有更好的类用于访问/导航 JSON。

之后,如果您需要/想要,您可以使用注释将每个问题反序列化为 POJO 并进行处理。这是我为 JSON Patch 操作所做的示例:

https://github.com/fge/json-patch/blob/master/src/main/java/com/github/fge/jsonpatch/JsonPatchOperation.java

这个文件会根据"op"的成员值是什么,生成JsonPatchOperation的不同实现;例如:

{ "op": "remove", "path": "/foo" }

将生成一个RemoveOperation

杰克逊一开始可能看起来很吓人;但是一旦你知道如何使用它,那就轻而易举了。

【讨论】:

  • 非常感谢。这是一个为期一周的徒劳练习,试图从JSON 响应手动创建U.I.。我使用过类、对象、for 循环等,它不仅速度慢而且非常复杂。我将查找 API 并开始学习。希望这是我一直在寻找的解决方案
  • 也请查看我编辑的答案。在反序列化方面,Jackson 实际上非常强大。
  • 如果您需要进一步的帮助,请不要犹豫 ;)
  • 实际上是最后一个问题。我已经在阅读 API 和我在第一次 Google 搜索中找到的第一对 tut 了。您是否知道任何可以展示杰克逊在行动中的好例子/tuts?
  • 嗯,我用它,所以是的,我有例子。这取决于你需要什么。我主要是 JSON 加载/JsonNode 导航的专家。对于初学者,请参阅here,它是如何加载 JSON 的一个很好的示例。读者请见here
【解决方案2】:

为您的问题构建一个 POJO 类:

Class Questions{
private String Name;
private String field_type;
private ArrayList option_value;
<Getter and Setters>
}

将其用作 POJO 类。并将其添加到 ArrayList。

只有在需要时才使用地图。使用 POJO/Business Objects 传输数据就足够了,而且最适合。

请告诉我你的想法。

【讨论】:

  • 我将尝试像 fge 推荐的那样使用 Jackson。感谢您的输入,这可以工作。我对POJO 一无所知,所以我也会调查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 2021-11-20
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多