实例化类中的变量的Android NullPointerException

时间:2014-05-30 00:33:45

标签: java android-listview constructor global-variables scope

我有一个调用expandablelistview的活动。这是一个非常香草的设置:

活动 - >创建expandablelistviewadapter->绘制它。

当调用getChildView并尝试引用通过listadapter的构造函数设置的变量时,它会收到一个NPE。

所以ActivityA->数据正确设置,然后发送到ArbitraryListAdapter。当引用childView方法并尝试使用dataFromActivityA时,我得到一个NullPointerException。我真的不确定为什么,当我在适配器类中验证dataFromActivityA时,它会正确验证。然后,当我尝试在getChildView方法中引用它时,NPE会出现。

用一个例子来解释:

class ActivityA extends Activity {

    private SparseArray<SparseArray<Object>> data;
    private ArbitraryListAdapter adapter;

    public void onCreate() {
        this.data = arbitraryFunctionToPopulateDataVariable(); // this properly populates
        this.adapter = new ArbitraryListAdapter(this, this.data);
        // do some other stuff

        this.adapter.notifyDataSetChanged();
    }
// do the rest of the activity here
}
/******************************/
class ArbitraryListAdapter extends BaseExpandableListAdapter {

    private SparseArray<SparseArray<Object>> dataFromActivityA;

    public ArbitraryListAdapter(Context context, SparseArray<SparseArray<Object>> x) {
        this.dataFromActivityA = x; // at this point the variable is set properly
    }

    public View getChildView(int group, int child, boolean last, View convertView, ViewGroup parent) {
        // Do some stuff
        // This is where the NPE arises!!!
        for(int i = 0;i< this.dataFromActivityA.size();i++){
            Log.d(TAG, "Group: " + i);
            for(int j = 0; j<this.dataFromActivityA.get(i).size();j++) {
                Log.d(TAG, "Child: " + this.dataFromActivityA.get(j).toString());
            }
            Log.d(TAG, "============================");
        }
    // Do some other stuff
    }
// Finish listadapter functions here
}

1 个答案:

答案 0 :(得分:0)

叹息我是世界上最差的开发者。我没有在我的onResume()中看到我清理列表的活动。我有多愚蠢!?