0

I have a problem when I query the sqlite database from the assets folder only when I uninstall the application and reinstall it. If it is the first time it is installed the application runs normally without any problem. In the list of errors shows me that the error is in the cursor but I do not understand the reason because when I install the application for the first time does not happen this. When I delete the data from the data folder it returns to normal operation.

Attached code:

    public class MainActivity extends AppCompatActivity {

ButtonRectangle button,button2;
EditText view;
private MyDatabase db;
ListView listView;
FloatingActionButton nuevaB;



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

    listView= (ListView) findViewById(R.id.listView);
    view = (EditText) findViewById(R.id.view);
    db = new MyDatabase(MainActivity.this);
    button2= (ButtonRectangle) findViewById(R.id.button2);
    button= (ButtonRectangle) findViewById(R.id.btnAceptar);

    nuevaB= (FloatingActionButton) findViewById(R.id.floatB);

    File database = getApplicationContext().getDatabasePath(MyDatabase.DBNAME);
    //Si la base de datos no existe

    if(false == database.exists()) {
        db.getReadableDatabase();
        //Copiar db
        if (copyDatabase(this)) {
            Toast.makeText(this, "Base de datos creada", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Error al crear la base de datos", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    nuevaB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent a=new Intent(getApplicationContext(),Registro.class);
            startActivity(a);
        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Buscar();
        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            view.setText("");
            view.setEnabled(true);
            button.setEnabled(true);
            cargaralimento();
        }
    });


    cargaralimento();
}
private boolean copyDatabase(Context context) { try {

    InputStream inputStream = context.getAssets().open(MyDatabase.DBNAME);
    String outFileName = MyDatabase.DBLOCATION + MyDatabase.DBNAME;
    OutputStream outputStream = new FileOutputStream(outFileName);
    byte[] buff = new byte[1024];
    int length = 0;
    while ((length = inputStream.read(buff)) > 0) {
        outputStream.write(buff, 0, length);
    }
    outputStream.flush();
    outputStream.close();
    return true;
} catch (Exception e) {
    e.printStackTrace();
    return false;
}
}

public void cargaralimento(){ ArrayList item=new ArrayList(); item=db.listarAlimentos();

ArrayAdapter<Alimento> adapter=new ArrayAdapter<Alimento>(this,android.R.layout.simple_list_item_1,item);
listView.setAdapter(adapter);
} }

Attached code helperSQL:

public class MyDatabase extends SQLiteOpenHelper {

public static final String DBNAME = "dbTest.db";
public static final String DBLOCATION = "/data/data/com.example.jinex.dbTest/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;

public MyDatabase(Context context) {
    super(context, DBNAME, null, 1);
    this.mContext = context;
}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

public void openDatabase() {
    String dbPath = mContext.getDatabasePath(DBNAME).getPath();
    if(mDatabase != null && mDatabase.isOpen()) {
        return;
    }
    mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}

public void closeDatabase() {
    if(mDatabase!=null) {
        mDatabase.close();
    }
}



public ArrayList<Alimento> listarAlimentos() throws SQLException{
    Alimento a=null;
    ArrayList<Alimento> item= new ArrayList<Alimento>();
    openDatabase();
    Cursor cursor=null;
    cursor = mDatabase.rawQuery("SELECT * FROM ALIMENTOS", null);
    cursor.moveToFirst();
    try{
    while (!cursor.isAfterLast()) {
       a=new Alimento(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getDouble(4),cursor.getDouble(5),cursor.getDouble(6),cursor.getDouble(7),cursor.getDouble(8),cursor.getDouble(9),cursor.getDouble(10),cursor.getDouble(11),cursor.getDouble(12),cursor.getDouble(13),cursor.getDouble(14),cursor.getDouble(15),cursor.getDouble(16),cursor.getDouble(17),cursor.getDouble(18),cursor.getDouble(19),cursor.getDouble(20),cursor.getDouble(21));
        item.add(a);
        cursor.moveToNext();
    }}catch (Exception e){
        Log.d("error",e.toString());
    }
    cursor.close();
    closeDatabase();
    return item;
}

Attached Error:

04-19 18:25:43.365 18263-18263/com.example.jinex.dbTest E/CursorWindow: Failed to read row 0, column 9 from a CursorWindow which has 635 rows, 9 columns.

04-19 18:25:43.367 18263-18263/com.example.jinex.dbTest D/error: java.lang.IllegalStateException: Couldn't read row 0, col 9 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

The database is in the assets folder and when the installation is run it is verified if it is in the phone. If it finds it does nothing otherwise copy it.

  • `when I query the sqlite database from the assets folder `. No. You are never doing that. You only copy the database file from assets to database folder. The queries will be done from the database in the database folder. – greenapps Apr 20 '17 at 08:15
  • `db.getReadableDatabase();`. Do not execute such statements if you have no database yet in the normal datsbase folder. You have more of such statements. – greenapps Apr 20 '17 at 08:19
  • I think you much better close your app the first time it runs after copying the database file. Display a nice toast to the user with info and request to start again. – greenapps Apr 20 '17 at 08:21
  • @greenapps Thanks for the councils but still does not execute the application the only way to do everything is normal is deleting the cache and the data of the application to run it for the second time. Delete the method you told me `db.getReadableDatabase();` but still the same error. – Jinex Velarde Apr 20 '17 at 09:40
  • Not enough. You have another db.... statement in onCreate. I asked you not to executr any db code the first run. – greenapps Apr 20 '17 at 09:44
  • You did not tell which of your code produces the posted errors. – greenapps Apr 20 '17 at 09:49
  • @greenapps thanks for answering. The error is in this line according to the console ` a=new Alimento(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getDouble(4),cursor.getDouble(5),cursor.getDouble(6),cursor.getDouble(7),cursor.getDouble(8),cursor.getDouble(9),cursor.getDouble(10),cursor.getDouble(11),cursor.getDouble(12),cursor.getDouble(13),cursor.getDouble(14),cursor.getDouble(15),cursor.getDouble(16),cursor.getDouble(17),cursor.getDouble(18),cursor.getDouble(19),cursor.getDouble(20),cursor.getDouble(21))` – Jinex Velarde Apr 20 '17 at 10:27
  • @greenapps `cargaralimento();` The console tells me that the problem is with the cursor but when it is installed by first it works normal. Also tell you to leave the onCreate method completely blank and try to show the results and the same error. – Jinex Velarde Apr 20 '17 at 10:30
  • Can you read that yourself? Are you asking us to read that? Please put all code in your post. – greenapps Apr 20 '17 at 10:30
  • @greenapps Thank you very much for the help. I enclose all the code in this link – Jinex Velarde Apr 20 '17 at 10:41
  • I will not follow that link. Post your relevant code here. – greenapps Apr 20 '17 at 10:44

0 Answers0