Android: getting Null Pointer Exception when inser

2019-07-20 12:21发布

I'm getting the error "java.lang.NullPointerException: Attempt to write to null array" when, after getting some data from database I have to put that data in a ArrayAdapter.

DatabaseHelper databaseHelper = new DatabaseHelper(this.getApplicationContext());

        List <Gasto> gastos;
        gastos = databaseHelper.getAllGastos();

        Gasto[] items=null;

        for(int i=0;i<gastos.size();i++)
        {
            items[i] = new Gasto(gastos.get(i).getMes(),gastos.get(i).getAno(), gastos.get(i).getDespesa_final());

        }

dataAdapter = new ArrayAdapter<Gasto>(this,android.R.layout.simple_list_item_1, items);

Can you please tell me how can I solve this error?

标签: java android
2条回答
We Are One
2楼-- · 2019-07-20 12:47

Gasto[] items = null; is the problem. Array is not created when you insert to it. Use Gasto[] items = new Gasto[gastos.size()];

查看更多
可以哭但决不认输i
3楼-- · 2019-07-20 12:53
Gasto[] items=null;

you have to create the array of Gastos before accessing it:

Gasto[] items = new Gastos[gastos.size()];
查看更多
登录 后发表回答