有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ImageAdapter从HashMap put方法返回NullPointerException

在适配器类中尝试向HashMap添加字符串值时,我遇到了NullPointerException:

HashMap<String,String> map = new HashMap<String, String>();
....
public class ImageAdapter extends BaseAdapter {
    ....
    //---Returns the number of images---
    public int getCount() {
        return getCursor.getCount();
    }
    ....
    //---Returns the ImageView view---
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null)   
           imageView = new ImageView(context);
        else 
           imageView = (ImageView) convertView;
        getCursor.moveToPosition(position);
        int imageID       = getCursor.getInt(columnIndex);    //--- Returns unique ID --
        String fileName   = getCursor.getString(arrayIndex);  //--- Returns  filepath --
        String imageValue = String.valueOf(imageID);
        try {
            map.put(imageValue, fileName);
        } catch (NullPointerException e) {
            Log.d("DEBUG", "Line154: " + e.toString());
            e.printStackTrace();
        } 
        Log.d("DEBUG", imageValue + " " + fileName);

我不理解这一点,因为上面的最后一行显示了正确的字符串值,那么为什么会出现错误呢?请告知


共 (2) 个答案

  1. # 1 楼答案

    变量“map”是否已初始化?我看不到它是在哪里设置或定义的,如果使用NullReference,我可能会怀疑您试图添加到的映射为null

  2. # 2 楼答案

    经过大量的额外研究,我现在可以自己回答这个问题了。需要的是一个带有 全局范围(这就是我最初在类外声明它的原因)。如何做到这一点 是通过在更改后扩展应用程序类,如下面的代码所示 允许这样做的XML清单(请参阅Google development):

    try {
        CustomHashMap thisMap = (CustomHashMap)getApplicationContext();
        thisMap.addKeyValue(imageValue,fileName);
    
        Log.d("DEBUG", "Line140 " + String.valueOf(thisMap.getSize()));
    } catch (NullPointerException e) {
        Log.d("DEBUG", "Line154: " + e.toString());
        e.printStackTrace();
    }
    ....
    public static class CustomHashMap extends Application {
        HashMap<String, String> myMap;
    
        public CustomHashMap() {
            super();
            this.myMap = new HashMap<String, String>();
        }
    
        public HashMap getMap() {
            return myMap;
        }
    
        public int getSize() {
            return myMap.size();
        }
    
        public void addKeyValue(String x, String y) {
            myMap.put(x,y);
        }
    }
    

    LogCat行现在正确地指示了每次迭代中单个HashMap的大小增加