简体   繁体   English

添加Hashmap时的ArrayList提供NPE

[英]ArrayList on adding Hashmap gives NPE

    subMap = new HashMap<String, String>();
    cursor = sdB.query(DataBase.TB, cols, null, null, null, null, null);
    cursor.moveToFirst();
    limit = 1;
    while(cursor.moveToNext()){
        limit +=1;
    }
    limit *= 2;
    cursor.moveToFirst();
    do{
        for(i=i+1; i<limit; i++){
            if(i%2!=0){
                subCode = cursor.getString(cursor.getColumnIndex(DataBase.C_CODE));
                subMap.put(TAG_SUB_CODE, subCode);
                Log.i("Alert", subCode);

                subjects.add(subMap);
                break;
            }
            else{
                subName = cursor.getString(cursor.getColumnIndex(DataBase.SUB_TITLE));
                subMap.put(TAG_SUB_NAME, subName);
                if(subMap.containsKey(TAG_SUB_NAME))
                    Log.i("Alert", "Yes");
                if(subMap.containsValue(subName))
                    Log.i("Alert", "Again Yes");
                Log.i("Alert", TAG_SUB_NAME);
                Log.i("Alert", subName);
                subjects.add(subMap);
            }
        }
    }while(cursor.moveToNext());

    cursor.close();

Gives me an NPE on subjects.add(subMap) in both if and else statement. 在if和else语句中subjects.add(subMap)我关于subjects.add(subMap)的NPE。 First else is executed then if. 首先执行其他,然后执行if。 But program stops at first encounter with it in else block. 但是程序在else块中第一次遇到它时就停止了。 Can Anyone please help me. 谁能帮帮我吗。 I checked the existance of value and key in hashmap and it returned me true ( yes and again yes ) in my log cat but still the subjects.add(subMap) returns an NPE. 我检查了hashmap中value和key的存在,它在我的日志猫中返回true( yesagain yes ),但是subject.add(subMap)仍然返回NPE。

Thank You 谢谢

You need to initialize your list subjects . 您需要初始化列表subjects For example like this: 例如这样:

ArrayList<HashMap<String, String>> subjects = new ArrayList<HashMap<String, String>>();

If you don't do that then at this line: 如果您不这样做,请在此行:

subjects.add(subMap);

an NPE will be thrown. NPE将被抛出。

Most likely subjects is null. 最有可能的subjects为空。 Have you initialized it like this: 您是否像这样初始化了它:

ArrayList<Map<String, String>> subjects = new ArrayList<Map<String, String>>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM