如何在ListView onItemClick中获取HashMap id值?

时间:2014-03-17 08:20:28

标签: android android-listview

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

但我无法在 onItemClick 方法中获取银行名称。任何人都可以帮我解决这个问题吗?

这是我的活动代码。

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

        }
    });
}

这是我的Adapter类

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错误。

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)

2 个答案:

答案 0 :(得分:3)

您有两个错误。首先,您尝试访问未初始化的成员类,因为您正在调整成员的类作用域,以使用本地作用域重新声明该变量。这很容易解决。你可以使用

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

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

 arg0.getItemAtPosition(arg2)

第二个错误是您将String投射到HashMap。您的getItem会返回:

map.get(mKeys[position]);

并且由于您在自定义适配器中声明了HashMap<String, String>getItem实际上是返回一个String实例。所以你有错误的演员。修复NPE后,您将获得ClassCastException

编辑:实现你想要的,你应该改变

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

    String key = mKeys[position];
    String Value = getItem(position).toString();
    
  3. 你的getItem看起来像:

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

    并且getView将以

    开头
       @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Pair<String, String> item = (Pair<String, String>)getItem(position);
            String Value = item.second;
        }
    
    在onItemClick里面你会得到类似的东西:

       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。您可以阅读this指南。

答案 1 :(得分:0)

您应该创建一个Bank对象,将其作为名称和徽标作为属性,然后将Bank对象的ArrayList传递给您的适配器。