java – NullPointerException when trying to open database

Question:

I'm trying to include in the DB an item that was selected, but trying to open the database using .open(); I'm getting a NullPointerException error.


After the user selects which item they want to save, I display an AlertDialog and ask them to confirm the addition. When the YES option is selected, it returns the error. Below is the part where it is generating the error and the LogCat.

public class CadPreVenda extends ListActivity{

private static final String[] FORMASDEPAGAMENTO = new String[]{"À VISTA - DINHEIRO","À VISTA - CHEQUE","À VISTA - CARTAO","À PRAZO - CARTAO","À PRAZO - CHEQUE","À PRAZO - CREDIARIO","À PRAZO - BOLETO BC"}; 

List<LCZ002> itensPV;
ItemPreVendaAdapter adapter;
ItemPreVendaDAO itemPVDAO;

//removed a piece of code that has no connection with the problem.

public void onActivityResult(int requestCode, int resultCode, Intent it) {

        Intent itquant = new Intent(CadPreVenda.this, pvItemQuantidade.class);
        if(it == null){
            Log.d("ERRO", "Algum erro encontrado"); 
        }
        else if (requestCode == 1){ 

            Bundle params = it !=null ? it.getExtras(): null;

            if (params != null ){
                final LCM001 produto = (LCM001) params.get("produto");
                if(requestCode == 0){
                    Toast.makeText(getApplicationContext(), "RequestCode = 0. Erro.", Toast.LENGTH_SHORT).show();
                }
                else{
                    new AlertDialog.Builder(this).setTitle("Produto: "+produto.getDescricao())
                    .setIcon(R.drawable.lupa)
                    .setMessage("Valor do produto: R$"+ produto.getVrVenda()+"\nConfirma inclusão do produto?")

                    .setNegativeButton("Não", new OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }//fim onClick
                    }) //fim onClickListener_NegativeButton

                    .setPositiveButton("Sim", new OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            int numPV=1;
                            int codItem= (int) produto.getId();
                            double valorItem = Double.parseDouble(produto.getVrVenda());
                            double quantidadeItem= 1;
                            String descricao = produto.getDescricao();
                            String unidade = produto.getUnidade();

                            LCZ002 itemPV = new LCZ002(numPV, codItem, valorItem, quantidadeItem, descricao, unidade);
                            itemPVDAO.open();// <<<<<< Aqui ocorre o erro.
                            itemPVDAO.novoItemPV(itemPV);
                            itemPVDAO.close();
                            //Fim Salva Item PV

                        }//fim onclick
                    })      /*fim onCLickListener*/
                    .show();
                }

            } //if (params != null )
        }//

LogCat:

06-17 10:00:44.614: E/AndroidRuntime(1300): FATAL EXCEPTION: main
06-17 10:00:44.614: E/AndroidRuntime(1300): Process: br.sysandroid, PID: 1300
06-17 10:00:44.614: E/AndroidRuntime(1300): java.lang.NullPointerException
06-17 10:00:44.614: E/AndroidRuntime(1300):     at br.sysandroid.CadPreVenda$3.onClick(CadPreVenda.java:179)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at android.os.Looper.loop(Looper.java:136)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at java.lang.reflect.Method.invokeNative(Native Method)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at java.lang.reflect.Method.invoke(Method.java:515)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-17 10:00:44.614: E/AndroidRuntime(1300):     at dalvik.system.NativeStart.main(Native Method)

ItemPreVendaDAO class

package br.sysandroid.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import br.sysandroid.dao.banco.BancoDAO;
import br.sysandroid.dao.banco.Lcz002DAO;
import br.sysandroid.model.LCZ002;

public class ItemPreVendaDAO {

    private SQLiteDatabase database;
    private BancoDAO bancoDAO;

    public ItemPreVendaDAO(Context context) {
        bancoDAO = new BancoDAO(context);
    }

    public void open() throws SQLException {
        database = bancoDAO.getWritableDatabase();
    }

    public void close() {
        bancoDAO.close();
    }


        public long novoItemPV(LCZ002 itemPV) {
            ContentValues values = new ContentValues();

            values.put(Lcz002DAO.CAMPO_NUM_PREVENDA, itemPV.getNumPV());
            values.put(Lcz002DAO.CAMPO_CODIGO_PRODUTO_ITENS, itemPV.getCodigoItemPV());
            values.put(Lcz002DAO.CAMPO_VALOR_UNITARIO_ITEM_PREVENDA, itemPV.getValorUnitarioPV());
            values.put(Lcz002DAO.CAMPO_QUANTIDADE_VENDIDA_ITEM_PREVENDA, itemPV.getQuantidadeItemPV());
            values.put(Lcz002DAO.CAMPO_DESCRICAO_ITEM_PREVENDA, itemPV.getDescricaoItemPV());
            values.put(Lcz002DAO.CAMPO_UNIDADE_ITEM_PREVENDA, itemPV.getUnidadeItemPV());
            return database.insert(Lcz002DAO.TABELA_PREVENDA_ITENS, null, values);

        }
}

Answer:

You just declared the ItemPreVendaDAO , you need to instantiate it:

itemPVDAO = new ItemPreVendaDAO();
itemPVDAO.open();
Scroll to Top