如何在ListView onItemClick 中获取HashMap id 值? [英] How to get HashMap id value in ListView onItemClick?

查看:19
本文介绍了如何在ListView onItemClick 中获取HashMap id 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将 ImageList 添加到我的应用程序中.我添加成功了.它显示了我被选中的银行的标志.我通过 HashMap 添加了这一点,因为我想在单击日志图像时取银行名称.

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.

但是我无法在 onItemClick 方法中获取银行名称.谁能帮我解决这个问题?

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

这是我的活动代码.

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);

        }
    });
}

这是我的适配器类

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 ;
        }
}

这是 LogCat 错误.

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)

推荐答案

您有两个错误.首先,您试图访问未初始化的成员类,因为您正在隐藏成员的类范围,并使用本地范围重新声明变量.这很容易修复.你可以使用

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) {

onItemClick 的第一个参数,用于检索位置处的元素.在你的情况下是:

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

 arg0.getItemAtPosition(arg2)

第二个错误是您将String 转换为HashMap.您的 getItem 返回:

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

map.get(mKeys[position]);

并且由于您在自定义适配器中声明了 HashMapgetItem 实际上是返回一个 String 实例.所以你有错误的演员.一旦你修复了 NPE,你就会得到一个 ClassCastException

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

要实现你想要的,你应该改变

to achieve what you want you should change from

  1. 将表单 HashMap 切换为另一种基于索引、基于顺序的集合.例如,它可以是 ArrayList>,或者您可以创建自己的 javabean.我将假设您将使用 Pair 类,将 id 作为第一个元素,将 url 作为第二个值
  2. 相应地更改 getViewgetItem.你可以摆脱

  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();

您的 getItem 将如下所示:

your getItem will look like:

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

和 getView 将以

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;
    }

在 onItemClick 里面你会得到类似的东西:

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;
    }

正如@Raghunandan 正确指出的那样,您应该将所有与网络/阻塞相关的操作放到不同的线程中.最简单的方法,android 友好,是使用 AsyncTask.您可以阅读指南.

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.

这篇关于如何在ListView onItemClick 中获取HashMap id 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆