samedi 27 février 2016

Working on a prebuilt Sqlite database Android

I want to interact with my Sqlite Database for my Android project. I put this database in my assets and at the beginning the database is copied in my application folder : "/data/data/com.company.sqlitetutorial/databases/" here all is working fine, but when I want to do some interaction with it like inserting a new line or getting any information from it, I already have an SQLiteLog: (1) no such table :"anytable" error. I tried to change the version of the database, nothing new happen, I tried to create my database and interact with it directly it works perfectly, so I didn't understand why when I use a preconfig database it doesn't work, can you help me please ?

here is the code for my Main activity :

package com.company.sqlitetutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /** Called when the activity is first created. */


        LivresBDD livreBdd = new LivresBDD(this);


        Livre livre = new Livre("123456789", "number 1");
        Livre livre2 = new Livre("123456733", "number 2");
        Livre livre3 = new Livre("123456229", "number 3");


        livreBdd.open();

        livreBdd.insertLivre(livre);
        livreBdd.insertLivre(livre2);
        livreBdd.insertLivre(livre3); 
        Livre livreFromBdd = livreBdd.getLivreWithTitre(livre.getTitre());

        if(livreFromBdd != null){ 
            Toast.makeText(this, livreFromBdd.toString(), Toast.LENGTH_LONG).show();

            livreFromBdd.setTitre("book modified");

            livreBdd.updateLivre(livreFromBdd.getId(), livreFromBdd);
        }
         livreFromBdd = livreBdd.getLivreWithTitre("book modified");

        if(livreFromBdd != null){ 
            Toast.makeText(this, livreFromBdd.toString(), Toast.LENGTH_LONG).show();

        } 
        livreFromBdd = livreBdd.getLivreWithTitre("book modified");

        if(livreFromBdd == null){

        }

        else{

            Toast.makeText(this, "book modified is here", Toast.LENGTH_LONG).show();
        }

        livreBdd.getAllBooks();
        livreBdd.close();

    }
}

LivresBDD for managed the database

package com.company.sqlitetutorial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.io.IOException;
import java.util.ArrayList;


public class LivresBDD {
    private static final int VERSION_BDD = 2;
    private static final String NOM_BDD = "eleves.db";

    private static final String TABLE_LIVRES = "table_livres";
    private static final String COL_ID = "ID";
    private static final int NUM_COL_ID = 0;
    private static final String COL_ISBN = "ISBN";
    private static final int NUM_COL_ISBN = 1;
    private static final String COL_TITRE = "Titre";
    private static final int NUM_COL_TITRE = 2;

    private SQLiteDatabase bdd;

    private MaBaseSQLite maBaseSQLite;

    public LivresBDD(Context context){

        maBaseSQLite = new MaBaseSQLite(context, NOM_BDD, null, VERSION_BDD);
        try {
            maBaseSQLite.createDataBase(context);
        } catch (IOException mE) {
            mE.printStackTrace();
        }
    }

    public void open(){

        bdd = maBaseSQLite.getWritableDatabase();
    }

    public void close(){

        bdd.close();
    }

    public SQLiteDatabase getBDD(){
        return bdd;
    }

    public long insertLivre(Livre livre){

        ContentValues values = new ContentValues();

        values.put(COL_ISBN, livre.getIsbn());
        values.put(COL_TITRE, livre.getTitre());

        return bdd.insert(TABLE_LIVRES, null, values);
    }

    public int updateLivre(int id, Livre livre){ 
        ContentValues values = new ContentValues();
        values.put(COL_ISBN, livre.getIsbn());
        values.put(COL_TITRE, livre.getTitre());
        return bdd.update(TABLE_LIVRES, values, COL_ID + " = " +id, null);
    }

    public int removeLivreWithID(int id){ 
        return bdd.delete(TABLE_LIVRES, COL_ID + " = " +id, null);
    }

    public Livre getLivreWithTitre(String titre){ 
        Cursor c = bdd.query(TABLE_LIVRES, new String[] {COL_ID, COL_ISBN, COL_TITRE}, COL_TITRE + " LIKE \"" + titre +"\"", null, null, null, null);
        return cursorToLivre(c);
    }

    public ArrayList<String> getAllBooks(){

        Cursor mCursor = bdd.rawQuery("SELECT * FROM "+TABLE_LIVRES,null);
        ArrayList<String> list = new ArrayList<>();
        if (mCursor.moveToFirst()) {

            while (mCursor.isAfterLast() == false) {
                String name = mCursor.getString(2);

                list.add(name);
                mCursor.moveToNext();
            }
        }

        if(list != null){
            for (int i = 0; i < list.size(); i++) {
                System.out.println("list.get(i) = " + list.get(i));
            }
        }

        return list;
    }

    private Livre cursorToLivre(Cursor c){

        if (c.getCount() == 0)
            return null;


        c.moveToFirst();

        Livre livre = new Livre(); 
        livre.setId(c.getInt(NUM_COL_ID));
        livre.setIsbn(c.getString(NUM_COL_ISBN));
        livre.setTitre(c.getString(NUM_COL_TITRE));

        c.close();


        return livre;
    }
}

This is the class to copy, open the database :

package com.company.sqlitetutorial;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MaBaseSQLite extends SQLiteOpenHelper {

    private static final String TABLE_LIVRES = "table_livres";
    private static final String COL_ID = "ID";
    private static final String COL_ISBN = "ISBN";
    private static final String COL_TITRE = "Titre";
    private static String DB_PATH = "/data/data/com.company.sqlitetutorial/databases/";

    private static String DB_NAME = "";

    private static final String CREATE_BDD = "CREATE TABLE " + TABLE_LIVRES + " ("
            + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_ISBN + " TEXT NOT NULL, "
            + COL_TITRE + " TEXT NOT NULL);";


    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public MaBaseSQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {

        super(context,name, factory, version);
        this.myContext = context;
        DB_NAME = name;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase(Context context) throws IOException {

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
            Toast.makeText(context, "La BDD existe", Toast.LENGTH_LONG).show();
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.

            this.getReadableDatabase();

            try {
                Toast.makeText(context, "Copy database", Toast.LENGTH_LONG).show();
                copyDataBase();

            } catch (IOException e) {
                e.printStackTrace();
                throw new Error("Error copying database");

            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            System.out.println("check database");
        }catch(SQLiteException e){

            //database does't exist yet.
            e.printStackTrace();
        }

        if(checkDB != null){

            checkDB.close();

        }
        System.out.println("checkDB "+checkDB);
        return checkDB != null ? true : false;
    }
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
        System.out.println("begin COPY");

        Log.i("Database",
                "New database is being copied to device!");
        byte[] buffer = new byte[1024];
        OutputStream myOutput;
        int length;
        // Open your local db as the input stream
        InputStream myInput;
        try
        {
            myInput =myContext.getAssets().open(DB_NAME);
            // transfer bytes from the inputfile to the
            // outputfile
            myOutput =new FileOutputStream(DB_PATH+ DB_NAME);
            while((length = myInput.read(buffer)) > 0)
            {
                myOutput.write(buffer, 0, length);
            }
            myOutput.close();
            myOutput.flush();
            myInput.close();
            Log.i("Database",
                    "New database has been copied to device!");

            System.out.println("close COPY");
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

    }


    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }
}

The last class :

package com.company.sqlitetutorial;

public class Livre {
    private int id;
    private String isbn;
    private String titre;

    public Livre(){}

    public Livre(String isbn, String titre){
        this.isbn = isbn;
        this.titre = titre;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitre() {
        return titre;
    }

    public void setTitre(String titre) {
        this.titre = titre;
    }

    public String toString(){
        return "ID : "+id+"\nISBN : "+isbn+"\nTitre : "+titre;
    }
}

Aucun commentaire:

Enregistrer un commentaire