Null value in database call (SQLite)

0

I'm doing an app that requires a database where when looking up / searching for a number in the first column of the database, the data that is in the second column corresponds to that data. The problem is that when I enter the number it returns a null value to me , I do not know what is failing me.

This is the code of the connection to the database and other

public class DB extends SQLiteOpenHelper {

private static String DB_PATH = "";

private static String DB_NAME = "Prueba.db";

private SQLiteDatabase myDataBase;

private final Context myContext;

public DB(Context context, String Prueba, SQLiteDatabase.CursorFactory factory, int version){
    super(context, DB_NAME, factory, 1);
    this.myContext = context;
    DB_PATH= myContext.getDatabasePath(DB_NAME).toString();
}


public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if(dbExist){
        //Si la base de datos ya existe -> no hagas nada
    }else{

        //Al llamar este metodo y cuando este la base de datos vacia se creara por defecto una en el system path
        //de mi propia aplicacion entonces se podra sobreescribir esa base de datos con la nuestra.
        this.getWritableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }

    }

}


/**
 * Si la base de datos ya existe evitar que se vuelva a copiar el archivo cada ves que se abre la aplicacion.
 * @return true si ya existe, false si no.
 */
private boolean checkDataBase() {
    //  this.getReadableDatabase();

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {


    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}


/**
 * Copia tu base de datos desde tu folder de assets (local) para que solo se cree la base de datos vacia
 * */
private void copyDataBase() throws IOException{

    InputStream myInput = myContext.getAssets().open(DB_NAME);

    String outFileName = DB_PATH ;

    OutputStream myOutput = new FileOutputStream(outFileName);

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

    //Cierra los streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws java.sql.SQLException {

    //Abre la base de datos
    String myPath = DB_PATH ;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

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

    super.close();

}

    @Override
public void onCreate(SQLiteDatabase db){

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){

}

public String[] buscar_reg(String buscar){
    String[] Orden = new String[3];
    //SQLiteDatabase database = this.getWritableDatabase();
    SQLiteDatabase database = this.getReadableDatabase();
    String q = "SELECT * FROM Orden WHERE no_orden ='" + buscar +"'";
    Cursor registros = database.rawQuery(q, null);
    if (registros.moveToFirst()){
        for (int i = 0; i<2; i++){
            Orden[i]=registros.getString(i);
        }
        Orden[2]="Encontrado";
    }else {
        Orden[2]="No se encontro la orden #"+buscar;
    }
    database.close();
    return Orden;
}

}

And then there is the MainActivity code that is where the "search engine" is located, in which you enter the number and it sends it to the activity of the connection to the database, at the end of the previous code it can be seen where does the operation to find the number in the corresponding column.

public class MainActivity extends AppCompatActivity {
EditText E_buscar;
TextView no_orden, estado;
Button B_buscar, B_Lista;
DB db ;

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

    no_orden = (TextView)findViewById(R.id.no_orden);
    estado = (TextView)findViewById(R.id.estado);

    E_buscar = (EditText)findViewById(R.id.E_buscar);

    B_buscar = (Button)findViewById(R.id.B_buscar);
    B_Lista = (Button)findViewById(R.id.B_Lista);
    db= new DB(this, "Orden", null, 1);

    fetchData();

    B_buscar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DB db = new DB(getApplicationContext(),null,null,1);
            String buscar = E_buscar.getText().toString();
            String[] Orden;
            Orden = db.buscar_reg(buscar);
            no_orden.setText("\nOrden #" + Orden[0] + "\n");
            estado.setText(Orden[1] + "\n");
            Toast.makeText(getApplicationContext(),Orden[2],Toast.LENGTH_SHORT).show();
        }
    });

}

public void fetchData() {
    db = new DB(this,"Orden", null, 1);
    try {

        db.createDataBase();
        db.openDataBase();

    } catch (Exception e) {
        e.printStackTrace();
    }

}
}

Thank you, I hope you can help me.

    
asked by Cesar Perez 24.10.2017 в 02:13
source

1 answer

1

You have not implemented the onCreate (SQLiteDatabase db) and onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) methods of your DB class.

The first of these methods is called when the database is first created. It is in this method that you have to create the tables in the database.

You should therefore implement this method. Something similar to this

@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL("CREATE TABLE " + DB_NAME + " (" + <nombre de columna> + <tipo de dato> + <,> ... + " )";
}

Anyway, you should review the documentation well. I leave a link where you can see an example of how to implement this class. Saving data in SQL databases

I hope it helps you

    
answered by 26.10.2017 / 20:09
source