android - Android 中的 JSON 到 listView

标签 android json list view

我正在尝试将 JSON 放入 ListView。我从 http://api.androidhive.info/contacts/ 获取数据(仅使用名称字段)我能够将它们放入数组,但无法将它们放入列表

[注意] 然而,ListView 恰好为 13 个条目(名称数量)生成了 13 行,但这些行是空白的

private class GetJidla extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(TableMenuActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                jidla = jsonObj.getJSONArray(TAG_CONTACTS);

                // looping through All Contacts
                for (int i = 0; i < jidla.length(); i++) {
                    JSONObject c = jidla.getJSONObject(i);

                  //  String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);


                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                  //  contact.put(TAG_ID, id);
                    contact.put(TAG_NAME, name);


                    // adding contact to contact list
                    jidlaList.add(contact);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }



        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                TableMenuActivity.this, jidlaList,
                android.R.layout.simple_list_item_1, new String[] {TAG_NAME}, new int[] {android.R.id.list,
                         });

        menu = (ListView)findViewById(android.R.id.list);
        menu.setAdapter(adapter); 

    } 

列表在这里

<ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip" >



    </ListView>

i need it to be on one screen, in one activity here is the image, the brown lsit is where i need it

Image

最佳答案

我有一个例子可以做到这一点:

public class MainActivity extends Activity {
     //json string
     private String jsonString = "{\"employee\":[{\"emp_name\":\"employee1\",\"emp_no\":\"101700\"},{\"emp_name\":\"employee2\",\"emp_no\":\"101701\"},{\"emp_name\":\"employee3\",\"emp_no\":\"101702\"},"+
            "{\"emp_name\":\"employee4\",\"emp_no\":\"101703\"},{\"emp_name\":\"employee5\",\"emp_no\":\"101704\"},{\"emp_name\":\"employee6\",\"emp_no\":\"101705\"},"+
            "{\"emp_name\":\"employee7\",\"emp_no\":\"101706\"},{\"emp_name\":\"employee8\",\"emp_no\":\"101707\"},{\"emp_name\":\"employee9\",\"emp_no\":\"101708\"},"+
            "{\"emp_name\":\"employee10\",\"emp_no\":\"101709\"},{\"emp_name\":\"employee11\",\"emp_no\":\"101710\"},{\"emp_name\":\"employee12\",\"emp_no\":\"101711\"},"+
            "{\"emp_name\":\"employee13\",\"emp_no\":\"101712\"},{\"emp_name\":\"employee14\",\"emp_no\":\"101713\"},{\"emp_name\":\"employee15\",\"emp_no\":\"101712\"}]}";
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      initList();
      ListView listView = (ListView) findViewById(R.id.listView1);
      SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] {"employees"}, new int[] {android.R.id.text1});
      listView.setAdapter(simpleAdapter);
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }

     List<Map<String,String>> employeeList = new ArrayList<Map<String,String>>();
     private void initList(){

      try{
       JSONObject jsonResponse = new JSONObject(jsonString);
       JSONArray jsonMainNode = jsonResponse.optJSONArray("employee");

      for(int i = 0; i<jsonMainNode.length();i++){
       JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
       String name = jsonChildNode.optString("emp_name");
       String number = jsonChildNode.optString("emp_no");
       String outPut = name + "-" +number;
       employeeList.add(createEmployee("employees", outPut));
      }
     }
      catch(JSONException e){
       Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
      }
     }

     private HashMap<String, String>createEmployee(String name,String number){
      HashMap<String, String> employeeNameNo = new HashMap<String, String>();
      employeeNameNo.put(name, number);
      return employeeNameNo;
     }

    }

我使用这个代码,它工作得很好!

代码来自JSON Exemple

关于android - Android 中的 JSON 到 listView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21602652/

相关文章:

json - 如何使用 Express 或 Body-Parser 拒绝无效的 JSON 正文

r - 取消列出 R 中矩阵列表的结构

android - 具有更多 ListView 的 AdapterView.OnItemClickListener

json - Alamofire 和 SwiftyJSON

android - 红米手机运行时权限

javascript - 选择带有 json 的 js 不起作用

Java - 获取对象的arrayList中最常见的元素

java - 使用 Gson 或 Xtream 将 Array Json 列表 <MyObject>

java - 覆盖锁定屏幕上的硬件音量按钮(设备处于唤醒状态)

Android : Difference between LocationManager. addProximityAlert() & LocationClient.addGeofences()