NullPointerException at android.widget.ArrayAdapter.createViewFromResource

家住魔仙堡 提交于 2019-12-04 05:01:26

Anyone please tell where i am wrong?

The thing you did wrong in your code is the way you initialize the CharSequence array in the getEntries method. Your code:

if (cursor.moveToFirst()){
    int i=0;
    do{
       size[i]=new String(cursor.getString(1)+"X"+cursor.getString(2));
       System.out.println(cursor.getString(1)+"X"+cursor.getString(2));
    }while(cursor.moveToNext());
}

You initialize the size array with the size of the Cursor and then you go in to the while loop above. The problem is that your while loop only sets the value for i = 0 as you don't increase i's value in that loop. For this reason your size array will have a value only for position 0 and null on all other positions. This will make the ArrayAdapter throw that NullPointerException.

The correct loop would be:

if (cursor.moveToFirst()){
    int i=0;
    do{
       size[i]=new String(cursor.getString(1)+"X"+cursor.getString(2));
       System.out.println(cursor.getString(1)+"X"+cursor.getString(2));
       i++;
    }while(cursor.moveToNext());
}

The full getEntries method would be:

private CharSequence[] getEntries() {
    Cursor cursor = SQLiteAdapter.queueAll();
    int num = cursor.getCount();        
    String[] size = new String[num];
    System.out.println(cursor.getCount());
    if (cursor.moveToFirst()) {         
        int i = 0;
        do {
            size[i] = new String(cursor.getString(1) + "X"
                    + cursor.getString(2));             
            i++;
        } while (cursor.moveToNext());
    }
    cursor.close();
    return size;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!