• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Connecting SQLite db file

Amine4499

Newbie
Hi everybody, I have a db file which is located in assets folder besides I've tried to connect the db in android studio but I failed the code don't contains any error but when I go to the activity that use the db the app stop

Here's the two classes that I use :
Java:
public class DbHelper extends SQLiteOpenHelper {

    private static DbHelper sInstance;
    private final Context myContext;

    private static final String DATABASE_NAME = "databases/firstAid.db.sql";
    private String DATABASE_PATH;
    private static int DATABASE_VERSION = 1;

    public static synchronized DbHelper getInstance (Context context){
        if (sInstance == null) { sInstance = new DbHelper(context); }
        return  sInstance;

    }

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
        String filesDir = context.getFilesDir().getPath();
        DATABASE_PATH = filesDir.substring(0, filesDir.lastIndexOf("/")) + "/databases/";

    }

    private boolean checkdatabase() {
        File dbfile = new File(DATABASE_PATH + DATABASE_NAME);
        return dbfile.exists();
    }

    private void copydatabase() {

        final String outFileName = DATABASE_PATH + DATABASE_NAME;

        InputStream myInput;
        try {
            // Ouvre la bdd de 'assets' en lecture
            myInput = myContext.getAssets().open(DATABASE_NAME);

            // dossier de destination
            File pathFile = new File(DATABASE_PATH);
            if(!pathFile.exists()) {
                if(!pathFile.mkdirs()) {
                    Toast.makeText(myContext, "Erreur : copydatabase(), pathFile.mkdirs()", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            // Ouverture en écriture du fichier bdd de destination
            OutputStream myOutput = new FileOutputStream(outFileName);

            // transfert de inputfile vers outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            // Fermeture
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
        catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(myContext, "Erreur : copydatabase()", Toast.LENGTH_SHORT).show();
        }

        // on greffe le numéro de version
        try{
            SQLiteDatabase checkdb = SQLiteDatabase.openDatabase(DATABASE_PATH + DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE);
            checkdb.setVersion(DATABASE_VERSION);
        }
        catch(SQLiteException e) {
            // bdd n'existe pas
        }

    } // copydatabase()

    @Override
    public void onCreate(SQLiteDatabase db) {


    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < newVersion){
            //Log.d("debug", "onUpgrade() : oldVersion=" + oldVersion + ",newVersion=" + newVersion);
            myContext.deleteDatabase(DATABASE_NAME);
            copydatabase();
        }

    }
}



Java:
public class ContactManager {

    private static final String TABLE_NAME = "contacts";
    private static final String NOM_CONTACT = "nom";
    private static final String NUMERO_CONTACT = "numero";
    private static final String SPECIFICATION_CONTACT = "specification";

    private static final String CREATE_TABLE_CONTACTS = "CREATE TABLE "+TABLE_NAME+
            " (" +
            " "+NOM_CONTACT+" TEXT," +
            " "+NUMERO_CONTACT+" INTEGER," +
            " "+SPECIFICATION_CONTACT+" TEXT" +
            ");";

    private DbHelper myDb;
    private SQLiteDatabase db;

    public ContactManager(Context context) {
        myDb = DbHelper.getInstance(context);
    }

    public void open() {
        db = myDb.getWritableDatabase();
    }

    public void close() {
        db.close();
    }

    public long ajouterContact(Contact contact) {

        ContentValues contentValues = new ContentValues();

        contentValues.put(NOM_CONTACT, contact.getNom());
        contentValues.put(NUMERO_CONTACT, contact.getNumero());
        contentValues.put(SPECIFICATION_CONTACT, contact.getSpecification());

        return db.insert(TABLE_NAME, null, contentValues);
    }




}
Java:
public class ContactManager {

    private static final String TABLE_NAME = "contacts";
    private static final String NOM_CONTACT = "nom";
    private static final String NUMERO_CONTACT = "numero";
    private static final String SPECIFICATION_CONTACT = "specification";

    private static final String CREATE_TABLE_CONTACTS = "CREATE TABLE "+TABLE_NAME+
            " (" +
            " "+NOM_CONTACT+" TEXT," +
            " "+NUMERO_CONTACT+" INTEGER," +
            " "+SPECIFICATION_CONTACT+" TEXT" +
            ");";

    private DbHelper myDb;
    private SQLiteDatabase db;

    public ContactManager(Context context) {
        myDb = DbHelper.getInstance(context);
    }

    public void open() {
        db = myDb.getWritableDatabase();
    }

    public void close() {
        db.close();
    }

    public long ajouterContact(Contact contact) {

        ContentValues contentValues = new ContentValues();

        contentValues.put(NOM_CONTACT, contact.getNom());
        contentValues.put(NUMERO_CONTACT, contact.getNumero());
        contentValues.put(SPECIFICATION_CONTACT, contact.getSpecification());

        return db.insert(TABLE_NAME, null, contentValues);
    }




}
 
Last edited:
Code:
04-08 23:25:28.551 9690-9690/? D/AndroidRuntime: CheckJNI is OFF
04-08 23:25:28.571 9690-9690/? D/dalvikvm: Trying to load lib libjavacore.so 0x0
04-08 23:25:28.571 9690-9690/? D/dalvikvm: Added shared lib libjavacore.so 0x0
04-08 23:25:28.571 9690-9690/? D/dalvikvm: Trying to load lib libnativehelper.so 0x0
04-08 23:25:28.571 9690-9690/? D/dalvikvm: Added shared lib libnativehelper.so 0x0
04-08 23:25:28.571 9690-9690/? D/dalvikvm: No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
04-08 23:25:28.591 9690-9690/? D/dalvikvm: Note: class Landroid/app/ActivityManagerNative; has 180 unimplemented (abstract) methods
04-08 23:25:28.711 9690-9690/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-08 23:25:28.711 9690-9690/? E/android.os.Debug: failed to load memtrack module: -2
04-08 23:25:28.831 9690-9690/? D/AndroidRuntime: Calling main entry com.android.commands.pm.Pm
04-08 23:25:28.861 9690-9690/? D/AndroidRuntime: Shutting down VM
04-08 23:25:28.861 9690-9697/? D/jdwp: Got wake-up signal, bailing out of select
04-08 23:25:28.861 9690-9697/? D/dalvikvm: Debugger has detached; object registry had 1 entries
04-08 23:26:02.201 1937-2910/com.bluestacks.bstfolder D/dalvikvm: GC_FOR_ALLOC freed 604K, 25% free 2768K/3648K, paused 3ms, total 3ms
 
Nope. :)
A stack trace is produced in the Logcat view, when your application crashes due to a runtime exception. An exception happens when your code does something unexpected and causes an error. The system then outputs a trace of what led your code to the point at which it caused the exception to be thrown. This allows you to understand where the exception happened, and hopefully why it happened. The stack trace will look something like this -

https://developer.android.com/studio/debug/stacktraces.html
 
It's doesn't show me errors like in the Logcat, the last lines are :
04-09 00:07:00.381 2064-3014/com.bluestacks.home I/Blue.Utils.AppSettingsApi: X-Path : /public/appsettings/.showrecommendedad_2.6.106.db
04-09 00:07:00.381 2064-3014/com.bluestacks.home I/Blue.Utils.AppSettingsApi: Response successful for file : .showrecommendedad.db
04-09 00:07:00.411 2064-3014/com.bluestacks.home D/Blue.Utils.Rooted: cp /storage/sdcard/Android/data/com.bluestacks.home/files/home/downloads/149818247 /data/data/com.bluestacks.home/files/.showrecommendedad.db
04-09 00:07:00.411 2064-3014/com.bluestacks.home D/Blue.Utils.Rooted: chmod 575 /data/data/com.bluestacks.home/files/.showrecommendedad.db
04-09 00:07:00.421 2064-3014/com.bluestacks.home I/Blue.: Downloaded file :/data/data/com.bluestacks.home/files/.showrecommendedad.db
04-09 00:07:00.421 2064-2064/com.bluestacks.home I/Blue.: success : /data/data/com.bluestacks.home/files/.showrecommendedad.db
04-09 00:07:13.441 1937-2910/com.bluestacks.bstfolder D/dalvikvm: GC_FOR_ALLOC freed 604K, 25% free 2768K/3648K, paused 8ms, total 8ms
04-09 00:08:03.451 1937-2910/com.bluestacks.bstfolder D/dalvikvm: GC_FOR_ALLOC freed 618K, 25% free 2768K/3648K, paused 8ms, total 8ms
04-09 00:08:48.461 1937-2910/com.bluestacks.bstfolder D/dalvikvm: GC_FOR_ALLOC freed 604K, 25% free 2768K/3648K, paused 7ms, total 7ms
04-09 00:09:38.481 1937-2910/com.bluestacks.bstfolder D/dalvikvm: GC_FOR_ALLOC freed 618K, 25% free 2768K/3648K, paused 8ms, total 8ms


upload_2017-4-9_0-11-51.png
 
Sorry to labour the point, but if your application crashed, it will have produced a stack trace. It's impossible to diagnose the problem just from that screenshot.
You need to post the stack trace, which will be shown in the Logcat window.
 
I've found it, sorry I'm a very beginner

Java:
                                                                            --------- beginning of crash
04-09 19:59:47.658 2511-2511/com.example.lkhedma.firstaid E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.lkhedma.firstaid, PID: 2511
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lkhedma.firstaid/com.example.lkhedma.firstaid.NouveauContact}: java.lang.IllegalArgumentException: File databases/firstAid.sql contains a path separator
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                             Caused by: java.lang.IllegalArgumentException: File databases/firstAid.sql contains a path separator
                                                                                at android.app.ContextImpl.makeFilename(ContextImpl.java:2165)
                                                                                at android.app.ContextImpl.getDatabasePath(ContextImpl.java:695)
                                                                                at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:644)
                                                                                at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:289)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.lkhedma.firstaid.ContactManager.open(ContactManager.java:33)
                                                                                at com.example.lkhedma.firstaid.NouveauContact.onCreate(NouveauContact.java:21)
                                                                                at android.app.Activity.performCreate(Activity.java:6679)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                at android.os.Looper.loop(Looper.java:154) 
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                                at java.lang.reflect.Method.invoke(Native Method) 
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 
It's not happy about the fact that you put a path separator in your database name

Code:
private static final String DATABASE_NAME = "databases/firstAid.db.sql";

change to

Code:
private static final String DATABASE_NAME = "firstAid.db.sql";

The DB Helper knows that the app's database is located in the database directory, so no need to include that in the name.
 
Thanks, but it doesnn't work :
04-09 20:56:40.475 8498-8498/com.example.lkhedma.firstaid E/SQLiteLog: (1) no such table: contacts
04-09 20:56:40.478 8498-8498/com.example.lkhedma.firstaid E/SQLiteDatabase: Error inserting specification=qsd numero=555 nom=dqsfq
android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: INSERT INTO contacts(specification,numero,nom) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1472)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.lkhedma.firstaid.ContactManager.ajouterContact(ContactManager.java:48)
at com.example.lkhedma.firstaid.NouveauContact$1.onClick(NouveauContact.java:36)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
04-09 20:56:40.478 8498-8498/com.example.lkhedma.firstaid I/System.out: succes
 
No, what I told you did solve your problem. You now have a different problem. Look at the stack trace, it tells you exactly what this new problem is.
 
Back
Top Bottom