android-获取listView中项的id

时间:2017-09-07 10:21:40

标签: android json listview android-arrayadapter

我正在使用JSON和php从mysql读取数据并将它们放入带有AsyncTask的listView中,我是 试图用setOnItemClickListener获取项目ID并烘烤它,但它显示我错误的ID,例如当我点击项目ID 4它显示我2 谢谢,如果你帮助我。

公共类ActivityList扩展了AppCompatActivity {

private String TAG = ActivityList.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

private String[] items ;

// URL to get contacts JSON
private static String url = "My URL";

ArrayList<HashMap<String, String>> contactList;


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

    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.listItems);

    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

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

        Log.e(TAG, "Response from url: " + jsonStr);

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

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("houseDB");

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

                    String name = c.getString("name");
                    String address = c.getString("address");
                    String telephone = c.getString("telephone");
                    String option = c.getString("option");
                    String ID = c.getString("ID");

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

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("address", address);
                    contact.put("telephone", telephone);
                    contact.put("option", option);
                    contact.put("ID", ID);

                    //put id row in array
                    items = new String[]{ID};

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });



        }

        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(
                ActivityList.this, contactList,
                R.layout.list_item, new String[]{"name", "address",
                "telephone", "option", "ID"}, new int[]{R.id.txtName,
                R.id.txtAddress, R.id.txtTelephone, R.id.txtOption, R.id.txtID});

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //get item id
                TextView itemID = (TextView) findViewById(R.id.txtID);
                String text = itemID.getText().toString();
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

            }
        });

    }

}

}

4 个答案:

答案 0 :(得分:1)

尝试使用联系人列表的列表项位置联系HashMap 获取ID,而不是从 TextView 文本获取ID,如下所示:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getApplicationContext(), contactList.get(position).get("ID"), Toast.LENGTH_SHORT).show();
      }
 });

答案 1 :(得分:0)

由于txtID会有多个与适配器关联的视图,因此您必须找到当前点击项目的txtID

TextView itemID = (TextView) view.findViewById(R.id.txtID);

答案 2 :(得分:0)

像这样使用

 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //get item id
            TextView ids = (TextView) findViewById(R.id.txtID);
            Contactlistyourclass co=new Contactlistyourclass();
            co=contactList.get(i)
            String d = co.getId(); // or what ever you have in your contactlist class as getter method!
            Toast.makeText(getApplicationContext(), d, Toast.LENGTH_SHORT).show();

        }
    });

}

答案 3 :(得分:0)

public static void main(String[] args) {
    int[] studentIdList = new int[] {1001,1002,1003};
    char[][] studentsGrades = new char[][] { { 'A', 'A', 'A', 'B' }, { 'A', 'B', 'B' } , { 'A', 'B', 'C' , 'D' }};
    charArrayToInt(studentsGrades,studentIdList);
    System.out.println("grade_test: "+studentsGrades[2][2]);
    System.out.println("grade_test: "+studentGradesInt[2][2]);
}