How to get HashMap id value in ListView onItemClick?

前端 未结 2 2019
悲&欢浪女
悲&欢浪女 2021-01-03 09:09

I tried to add ImageList to my application. i added it successfully. It shows Logos of banks which i was selected. I added that through HashMap, because i w

2条回答
  •  孤城傲影
    2021-01-03 09:58

    You have two errors. First you are trying to access a member class that is not intialized, since you are hding the member's class scoping redeclaring the variable with local scope. This is easily fixable. You can use

        @Override
        public void onItemClick(AdapterView arg0, View arg1, int arg2,
                long arg3) {
    

    the firs argument of onItemClick to retrieve the element at position. In your case it is:

     arg0.getItemAtPosition(arg2)
    

    the second error is that you are casting a String to HashMap. Your getItem returns:

    map.get(mKeys[position]);
    

    and since you declared HashMap in your custom adapter, getItem is actually return a String instance. So you have the wrong cast. As soon as you fix the NPE you will get a ClassCastException

    Edit: to achieve what you want you should change from

    1. Switch form HashMap to another kind, index, order based collection. It could be, for instance an ArrayList>, or you can create your own javabean. I will assume that you are going to use the Pair class, with the id as first element, and the url as second value
    2. Change getView and getItem accordingly. You can get rid

      String key = mKeys[position];
      String Value = getItem(position).toString();
      

    your getItem will look like:

    @Override
    public Object getItem(int position) {
        return dataset.get(position);
    }
    

    and getView will start with

       @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Pair item = (Pair)getItem(position);
            String Value = item.second;
        }
    

    inside onItemClick you'll get a similar thing:

       list.setOnItemClickListener(new OnItemClickListener() {
    
        @Override
        public void onItemClick(AdapterView arg0, View arg1, int arg2,
                long arg3) {
           Pair item = (Pair)arg0.getItemAtPosition(arg2);
           String id = item.first;
        }
    

    as correctly pointed out by @Raghunandan, you should all the Network/Blocking related operations into a different thread. The mostly easy way, android friendly, is to use an AsyncTask. You can read this guide.

提交回复
热议问题