How to get HashMap id value in ListView onItemClick?

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 want to take bank name when click the log image.

But i can't get the bank name in onItemClick method. Can anyone help me to fix this problem?

This is my Activity code.

public void getImageData() {

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

    try {
        JSONObject jsonResponse = new JSONObject(strJson1);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");

        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            img_url = jsonChildNode.optString("logo");
            String test1 = img_test_url + img_url;
            bName = jsonChildNode.optString("name");
            map.put(bName, test1);

        }

        ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),map);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Connection Error...",
                Toast.LENGTH_LONG).show();
    }

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

            HashMap<String, String> obj = (HashMap<String, String>) adapter.getItem(arg2);
            String name = (String) obj.get("bName");
            Log.d("Bank Name", name);

        }
    });
}

This is my Adapter class

public class ItemsAdapter extends BaseAdapter {

    private final Context context;
    ImageView imageView;
    private String[] mKeys;
    HashMap<String, String> map;

    ItemsAdapter(Context context, HashMap<String, String> map) {

        this.context = context;
        this.map = map;
        mKeys = map.keySet().toArray(new String[map.size()]);
}

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return map.size();
    }

    @Override
    public Object getItem(int position) {

        return map.get(mKeys[position]);
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

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

            LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = convertView;
            if (null == convertView)
                rowView = inflater.inflate(R.layout.items, parent, false);
            imageView = (ImageView) rowView.findViewById(R.id.imageView1);
            Bitmap bitmap;
            URL imageURL = null;


            Log.d("value", Value);
            Log.d("key", key);
        try {
            imageURL = new URL(Value);
        }

        catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();

            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {

            e.printStackTrace();
        }

            return rowView ;
        }
}

This is LogCat error.

03-17 13:58:13.620: E/AndroidRuntime(10172): FATAL EXCEPTION: main
03-17 13:58:13.620: E/AndroidRuntime(10172): java.lang.NullPointerException
03-17 13:58:13.620: E/AndroidRuntime(10172):    at com.example.testhashimage.MainActivity$1.onItemClick(MainActivity.java:161)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.widget.AdapterView.performItemClick(AdapterView.java:301)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.widget.AbsListView.performItemClick(AbsListView.java:1280)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3071)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.widget.AbsListView$1.run(AbsListView.java:3973)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.os.Handler.handleCallback(Handler.java:615)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.os.Looper.loop(Looper.java:137)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at android.app.ActivityThread.main(ActivityThread.java:4960)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at java.lang.reflect.Method.invokeNative(Native Method)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at java.lang.reflect.Method.invoke(Method.java:511)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
03-17 13:58:13.620: E/AndroidRuntime(10172):    at dalvik.system.NativeStart.main(Native Method)

Answers


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<String, String> 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<Pair<String, String>>, 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<String, String> item = (Pair<String, String>)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<String, String> item = (Pair<String, String>)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.


You should create a Bank object that as a name and a logo as attributes and then pass an ArrayList of bank objects to your adapter.


Need Your Help

Returning 404 in Angular

angularjs model-view-controller http-status-code-404

I'm familiar with returning 404 as the HTTP status code when you visit pages that do not exist. When you build static web sites, it works well and it makes sense, but in Angular it's different.