2

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?

1
  • 1
    You have this line of code "Gasto[] items = null;" which surely causes a NPE. Commented Feb 23, 2015 at 19:54

2 Answers 2

6
Gasto[] items=null;

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

Gasto[] items = new Gastos[gastos.size()];
Sign up to request clarification or add additional context in comments.

2 Comments

I do know it, but if I do what you said, I can't do this "items[i] = new Gasto(gastos.get(i).getMes(),gastos.get(i).getAno(), gastos.get(i).getDespesa_final());"
why you can't? What I wrote allocates memory for the array. what you wrote create the object you want to store into the array. Both are needed.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.