Error in Database

1

I'm creating a database, and this is the code I have in JAVA:

 String strNombre = nom.getText().toString();
            String strPregCinco = preg5.getText().toString();
            String strPregCuatro = preg4.getText().toString();


            if(strNombre.matches("") || strPregCinco.matches("") || strPregCuatro.matches(""))
            {
                Toast.makeText(context,"¡Dejaste campos vacíos!",Toast.LENGTH_LONG).show();
            }

            else if(botonun.isChecked() == false && botondo.isChecked() == false && botontr.isChecked() == false && botoncu.isChecked() == false && botonci.isChecked() == false
                    && botonse.isChecked() == false && botonsi.isChecked() == false && botonoc.isChecked() == false && botonnu.isChecked() == false && botondi.isChecked() == false
                    && botonon.isChecked() == false && botondc.isChecked() == false)
            {
                Toast.makeText(context,"¡No marcaste ninguna respuesta!",Toast.LENGTH_LONG).show();
            }
            else if(db != null)
            {
                db.execSQL("INSERT INTO Encuestado (strNombre, strPregCinco, strPregCuatro, ) " +
                        "VALUES (" + strNombre + ", '" + strPregCinco + ", '" + strPregCuatro + "')");
                Intent pas = new Intent(encuesta.this, MainActivity.class);
                Toast.makeText(context,"¡Encuesta enviada!",Toast.LENGTH_LONG).show();
                startActivity(pas);
            }
            db.close();

The problem is in else if(db != null) , since before I did not have it and everything worked perfect.

When I hit the "Send Survey" button, the if / else if condition is executed, and when the elseif(db != null) is executed, the crash appears, and the application stops, I need help! Thanks.

    
asked by Pablo Gonzalez 06.03.2017 в 13:23
source

1 answer

0

You have the db.close() out of the test if db is null . That causes you a NullPointerException in the case that db==null . Use a try... catch or keep the closure within the condition.

    
answered by 06.03.2017 в 15:53