0

I'm using a database which I get it externally from the sdcard. Also I have a data-source as an interface which I've written to manage database transactions. Here's how I get db from the sdcard:

File dbFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Database/MyDB.db");
SQLiteDatabase database = SQLiteDatabase.openSQLiteDatabase.openOrCreateDatabase(dbFile, null);
dataSource = new DataSource(getApplicationContext(), database);

importData(this); // Insert initial data in all tables in database

And here's the DataSource class:

public class DataSource {

    private SQLiteDatabase db;

    public WordsDS(Context context, SQLiteDatabase database) {
        db = database;
    }

    public void open() throws SQLException {}

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

    // Transaction Methods...
}

When I try to insert data to one of my tables in the db, it crashes and LogCat outputs:

Error inserting ...
E/Database(19416): android.database.sqlite.SQLiteException: no such table: ...

I don't know how I relate my db class which is below to that database I've created above. Need help.

public class DB extends SQLiteOpenHelper {

    static final String DATABASE_NAME = "MyDB";

    static final String TermTable = "Terms";
    static final String ID = "id";
    static final String Term = "term";
    static final String Type = "type";

    public static final int DATABASE_VERSION = 1;

    private static final String TERM_TABLE_CREATE = "Create table " + TermTable +
        "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
        Term + " VARCHAR(20) ," +
        Type + " VARCHAR(10))";

    public WordsDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    db.execSQL(TERM_TABLE_CREATE);
        db.execSQL(DEF_TABLE_CREATE);
        db.execSQL(HISTORY_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS " + TermTable);
        onCreate(db);
    }

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ali Allahyar
  • 341
  • 2
  • 11
  • 22

1 Answers1

0

There is only two areas I had to change my code:

In DB class:

// Give the path which I want to store my db in
public WordsDB(Context context, String path) {
    super(context, path + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
}

and in DataSource class:

public class DataSource {

    private DB dbHelper;
    private SQLiteDatabase db;

    public DataSource(Context context, String path) {
        dbHelper = new DB(context, path);
    }

    public void open() throws SQLException {
        db = dbHelper.getWritableDatabase();
    }

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

    // Transaction Methods...
}

Thanks Moyeen.

Ali Allahyar
  • 341
  • 2
  • 11
  • 22