-1

I'm connecting SQLite in NATIVE on android.

I'm Got this exception: unable to open database file

my NDK code:

#include <android/log.h>
#include <stdint.h>
#include "DatabaseHelper.h"
#include "../sqlite/sqlite3.h"

const char* SQL = "CREATE TABLE IF NOT EXISTS foo(a,b,c); INSERT INTO FOO 
VALUES(1,2,3); INSERT INTO FOO SELECT * FROM FOO;";
const int ERROR_STATE = -1;
const int SUCCESSFULLY_STATE = 0;

int createDatabase() {
char TAG[20] = "NATIVE_SQL";
sqlite3 *db = 0; // хэндл объекта соединение к БД
char *err = 0;

// открываем соединение и тут вылетает ошибка! 
if(sqlite3_open("myDb.db", &db)) {
    __android_log_print(ANDROID_LOG_DEBUG, TAG, "Error opened database. 
%s\n",sqlite3_errmsg(db));
    return ERROR_STATE;
}
...someone code

P.S. if if(sqlite3_open("", &db)) {.. database created temporary file and remove it durning close. If open("",&db) is work!

How will I create the db connection with "myDb.db" name?


Or

if(sqlite3_open_v2("myDb.db", &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL)) {
    __android_log_print(ANDROID_LOG_DEBUG, TAG, "Error opened database2. %s\n",sqlite3_errmsg(db));
    return ERROR_STATE;
}

Permissions in Manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
too honest for this site
  • 12,050
  • 4
  • 30
  • 52

1 Answers1

0

Android app does not have its own 'home' directory. The underlying Linux-like runtime has getcwd(), and it will return / - i.e. the root of the filesystem. Note that the app does not own / and it cannot write to this directory.

This means that you must pass the full path to any file you want to open, including myDb.db. You probably want to keep the database in the default database location for the app, such as returned by Context.getDatabasePath(). The best easiest reliable way to get it in C++, is to have Java query it before calling native, and pass the path to C++.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307