-2

I need to use a database already populated and display its data in a list, I searched the internet and found the solution using a DB file and passing to SQLite, however, I am having difficulty importing the SQLite database from assents from android for my project, I followed this tutorial, but in my case it has this error:

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Code - DataBaseHelper

public class DataBaseHelper extends SQLiteOpenHelper {
public static final String BD_NOME = "bdtestesqlite.db";
public static final String LOCAL = "/data/data/com.example.mts_rodrigues.myapplication/databases/";
private Context mContext;
private SQLiteDatabase sqLiteDatabase;

public DataBaseHelper(Context context){
    super(context, BD_NOME, null, 1 );
    this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

public void abrirBD(){
    String pacote = mContext.getDatabasePath(BD_NOME).getPath();

    if(sqLiteDatabase != null && sqLiteDatabase.isOpen()){
        return;
    }

    sqLiteDatabase = SQLiteDatabase.openDatabase(pacote, null, SQLiteDatabase.OPEN_READWRITE);
}

public void fecharBD(){
    if(sqLiteDatabase != null){
        sqLiteDatabase.close();
    }
}

public List<Produtos> getListaProdutos(){
    Produtos p = null;
    List<Produtos> lista = new ArrayList<>();
    abrirBD();
    Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM bd_produtos", null);
    c.moveToFirst();
    while(!c.isAfterLast()){
        p = new Produtos(c.getInt(0), c.getString(1), c.getString(2),c.getString(3), c.getString(4));
        lista.add(p);
        c.moveToNext();
    }
    c.close();
    fecharBD();

    return lista;

 }
}

Code - Main

private ListView lv;
private ListaAdapter adapter;
private List<Produtos> lista;
private DataBaseHelper dataBaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lv = (ListView) findViewById(R.id.lv);

    dataBaseHelper = new DataBaseHelper(this);

    File data = getApplicationContext().getDatabasePath(DataBaseHelper.BD_NOME);
    if(false == data.exists()){
        dataBaseHelper.getListaProdutos();

        if(copiarBD(this)){
            Toast.makeText(this, "Copiado com sucesso", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Erro ao copiar", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    lista = dataBaseHelper.getListaProdutos();

    adapter = new ListaAdapter(this, lista);

    lv.setAdapter(adapter);
}

private boolean copiarBD(Context context){
    try {

        InputStream inputStream = context.getAssets().open(DataBaseHelper.BD_NOME);
        String outFile = DataBaseHelper.LOCAL + DataBaseHelper.BD_NOME;
        OutputStream outputStream = new FileOutputStream(outFile);
        byte[] buff = new byte[1024];
        int legth = 0;
        while((legth = inputStream.read(buff)) > 0){
            outputStream.write(buff,0, legth);
        }

        outputStream.flush();
        outputStream.close();
        Log.v("Main", "Copiado");
        return true;

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

 } 
}

Code - ListAdapter

private Context context;
private List<Produtos> lista_produtos;

public ListaAdapter(Context context, List<Produtos> lista_produtos) {
    this.context = context;
    this.lista_produtos = lista_produtos;
}

@Override
public int getCount() {
    return lista_produtos.size();
}

@Override
public Object getItem(int i) {
    return lista_produtos.get(i);
}

@Override
public long getItemId(int i) {
    return lista_produtos.get(i).getId();
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View v = View.inflate(context, R.layout.item_lista,null);
    TextView nome = (TextView) v.findViewById(R.id.txt_nome_produto);
    TextView categoria = (TextView) v.findViewById(R.id.txt_categoria);
    TextView unidade = (TextView) v.findViewById(R.id.txt_unidade);

    nome.setText(lista_produtos.get(i).getNome_completo());
    categoria.setText(lista_produtos.get(i).getCategoria());
    unidade.setText(lista_produtos.get(i).getUnidade());
    return v;
 }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Get rid of that code and [use `SQLiteAssetHelper`](https://github.com/jgilfelt/android-sqlite-asset-helper). – CommonsWare Feb 06 '18 at 12:52
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Feb 06 '18 at 19:53

1 Answers1

0

make sure you have added

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

to your project's AndroidManifest.xml file if you are running your app on Android's Marshmallow or later version (API level 23 or greater)

Arpan Sarkar
  • 2,301
  • 2
  • 13
  • 24