Error calling sqlite database

1

I am learning to create an app, specifically, get a data from a bd already created and set it in a text. I followed several tutorials but I get an error (the code itself does not show any errors, but the app crashes).

This is the class of the database:

public class ManejadorBaseDeDatos extends SQLiteAssetHelper {

private static String DB_PATH = "data/data/com.xxkuakxxgmail.knowyourchamp/databases/";
private static String DB_NAME = "imcEmbar.db";

private static SQLiteDatabase mDataBase;

private static ManejadorBaseDeDatos sInstance = null;

private static final int DATABASE_VERSION = 1;


public ManejadorBaseDeDatos() {
    super(MainActivity.activity, DB_NAME, null, DATABASE_VERSION);

    try {
        createDataBase();
        openDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static ManejadorBaseDeDatos instance() {

    if (sInstance == null) {
        sInstance = new ManejadorBaseDeDatos();
    }
    return sInstance;
}


private void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();
    SQLiteDatabase db_Read = null;

    if (dbExist) {

    } else {

        db_Read = this.getReadableDatabase();
        db_Read.close();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error");
        }
    }
}

public boolean checkDataBase()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

public void copyDataBase() throws IOException {

    InputStream myInput = MainActivity.activity.getAssets().open(DB_NAME);

    String outFileName = DB_PATH + DB_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();

}

private void openDataBase() throws SQLException {

    String myPath = DB_PATH + DB_NAME;
    mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}


public Cursor select(String query) throws SQLException {
    return mDataBase.rawQuery(query, null);
}

@Override
public synchronized void close() {

    if (mDataBase != null)
        mDataBase.close();

    super.close();

}

This is the class where I want to call the bd:

public class Imc_Ema extends AppCompatActivity {

Button btnCalcular;
EditText txtIngresoSemanas;
EditText txtResultado;
ManejadorBaseDeDatos manejadorBD;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imc_adultos);

    manejadorBD = ManejadorBaseDeDatos.instance();
    btnCalcular = (Button)findViewById(R.id.btnCalcular);
    txtIngresoSemanas = (EditText) findViewById(R.id.txtIngresoSemanas);

    btnCalcular.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            txtResultado.setText(null);
            Double semanas = Double.valueOf(txtIngresoSemanas.getText().toString());
            Cursor cursor = manejadorBD.select("SELECT NormaMin FROM imcEmb WHERE Codigo_producto = '" + semanas + "' ");
            String consulta = cursor.getString(cursor.getColumnIndex("NormaMin"));
            txtResultado.setText(consulta);
        }
    });
}

}

And this is the error:

12-04 22:07:59.433 13916-13916/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: com.xxkuakxxgmail.knowyourchamp, PID: 13916
                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxkuakxxgmail.knowyourchamp/com.xxkuakxxgmail.knowyourchamp.Imc_Ema}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
                                                   at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
                                                   at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
                                                   at com.xxkuakxxgmail.knowyourchamp.ManejadorBaseDeDatos.<init>(ManejadorBaseDeDatos.java:0)
                                                   at com.xxkuakxxgmail.knowyourchamp.ManejadorBaseDeDatos.instance(ManejadorBaseDeDatos.java:46)
                                                   at com.xxkuakxxgmail.knowyourchamp.Imc_Ema.onCreate(Imc_Ema.java:25)
                                                   at android.app.Activity.performCreate(Activity.java:6705)
                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                   at android.os.Looper.loop(Looper.java:154) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
    
asked by Çhristofer Parra 05.12.2017 в 02:16
source

2 answers

1

The error is specified as:

  

Caused by: java.lang.NullPointerException: Attempt to invoke virtual   method 'android.content.pm.ApplicationInfo   android.content.Context.getApplicationInfo () 'on a null object   reference

You are trying to call the getapplicationinfo method () from a null instance of Context. Because you are incorrectly performing an instantiation of ManejadorBaseDeDatos .

The problem is that you are not defining the context, in this case you must define the value of the variable activity , which is used within the class ManejadorBaseDeDatos , must be made of this Form:

public class Imc_Ema extends AppCompatActivity {

Button btnCalcular;
EditText txtIngresoSemanas;
EditText txtResultado;

//*Agregar variable activity
public static Activity activity;
ManejadorBaseDeDatos manejadorBD;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imc_adultos);

    //* Importante definir esta variable, que es usada dentro de la clase ManejadorBaseDeDatos. 
    activity = this;         
    manejadorBD = ManejadorBaseDeDatos.instance();

    btnCalcular = (Button)findViewById(R.id.btnCalcular);
    txtIngresoSemanas = (EditText) findViewById(R.id.txtIngresoSemanas);

    btnCalcular.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            txtResultado.setText(null);
            Double semanas = Double.valueOf(txtIngresoSemanas.getText().toString());
            Cursor cursor = manejadorBD.select("SELECT NormaMin FROM imcEmb WHERE Codigo_producto = '" + semanas + "' ");
            String consulta = cursor.getString(cursor.getColumnIndex("NormaMin"));
            txtResultado.setText(consulta);

          //*Siempre cerrar cursor al terminar de obtener datos!
          cursor.close();
        }
    });
}
    
answered by 05.12.2017 в 19:26
-1

Here I leave a functional code. You can add the necessary algorithms to implement the rest of the SQL statements

public class VentasRepository extends SQLiteOpenHelper{
private static int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "cerveceria";
private static String DATABASE_TABLE = "Ventas";
private SQLiteDatabase sql = null;

public VentasRepository(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE = "CREATE TABLE "+DATABASE_TABLE+"("
            + "id TEXT PRIMARY KEY NOT NULL, "
            + "idUsuarios TEXT NOT NULL, "
            + "idCervezas TEXT NOT NULL, "
            + "idModalidades TEXT NOT NULL, "
            + "cantidad TEXT NOT NULL "
            + ")";

    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

    // Create tables again
    onCreate(db);
}

public List<Ventas> findAll() {
        List<Ventas> todos = new ArrayList<>();
        Reflexion reflexion = null;
        Ventas entidad = null;
    try {

        sql = this.getWritableDatabase();
        Cursor cursor = sql.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);

        if (cursor.moveToFirst()) {
            do {
                entidad = new Ventas(); // Creando una clase vacia
                reflexion = new Reflexion<Ventas>(entidad); // Creando una reflexion para cada clase entidad nueva

                for(int i=0; i<cursor.getColumnCount(); i++) {
                    reflexion.setValor(cursor.getColumnName(i),cursor.getString(i));//Almacenando valor para una sola entidad
                }

                todos.add(entidad);//Almacenando la entidad en una lista de entidades.

            } while (cursor.moveToNext());
        }

    }catch (Exception e){
        e.printStackTrace();
    }finally {
        if(sql!=null) sql.close();
    }
    return todos;
}

}
    
answered by 05.12.2017 в 04:47