【问题标题】:Problem with Arraylist and Hashmap when populating Listview填充 Listview 时 Arraylist 和 Hashmap 的问题
【发布时间】:2020-02-13 11:30:08
【问题描述】:

我正在尝试将数据从我的 JSON 文件获取到 HashMap,然后到我的 Arraylist,它应该显示在 Listview 中。但它没有显示任何东西。你能帮帮我吗?

公共类 SendPostRequest 扩展 AsyncTask {

    String data ="";
    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {

       try{


                JSONArray json = new JSONArray(data);
                ArrayList<HashMap<String, String>>  arrayList = new ArrayList<HashMap<String, String>>();

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

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

                    map.put("id", String.valueOf(i));
                    map.put("Name", "Vorname: " + e.getString("meta_value"));
                    map.put("orderid", "id: " + e.getString("post_id"));
                    arrayList.add(map);
                    //return map.toString();
                }

                    ArrayAdapter arrayAdapter = new ArrayAdapter(activity2.this, android.R.layout.simple_list_item_1,arrayList);

                }catch (JSONException e){
                    Log.e(this.getClass().getName(), "Some JSON error occurred" + e.getMessage());

                }
                return data;


            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

【问题讨论】:

  • 您好,欢迎来到 StackOverflow。我强烈建议您按照this StackOverflow article 的指南编辑您的问题。因为 StackOverflow 并不是用来帮助您调试代码的论坛。您可能还想通过tour 更熟悉 SO 和预期内容。

标签: java android arrays json listview


【解决方案1】:

要填充列表视图,您需要在创建数组适配器后添加这段代码

ListView myListView = (ListView) findViewById(R.id.idOfYourListView)

runOnUiThread(new Runnable() 
{
    @Override
    public void run()
    {
     myListView.setAdapter( arrayAdapter );
    }
});

【讨论】:

  • 它出现错误消息:“异常:只有创建视图层次结构的原始线程才能触摸此视图”
【解决方案2】:

从现在开始你应该用 RecyclerView 替换 ListView

【讨论】:

    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多