Put Database Into Android Project
Solution 1:
It doesn't pretend to be the best way, but that is how I made it in my project: Your database should be in res/assets directory. And here is a part of my DataBaseHelper class that might be helpful for you:
public class DataBaseHelper {
private static final String DB_NAME = "yourname.db";
private Context mContext;
private SQLiteDatabase mSQLiteDatabase;
public DataBaseHelper(Context context) {
mContext = context;
}
public void openOrCreate() {
File dbFile = mContext.getDatabasePath(DB_NAME);
if (!dbFile.exists())
copyDatabase(dbFile);
mSQLiteDatabase = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
}
private void copyDatabase(File dbFile) {
InputStream is = null;
OutputStream os = null;
try {
mContext.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
is = mContext.getAssets().open(DB_NAME);
os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) os.close();
if (is != null) is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Solution 2:
If you want to have a preloaded db, then the general approach is 1. put the sqlite file in the asset folder. 2. copy that file to the data directory.
Fortunately, there is a very simple & easy to use Git library Android Asset Helper. Have a look at their usage example.
Solution 3:
You have to create a class (.java file) that handles the database for you. That class automatically creates the SQLite database in your android devide. For example, this is a sample code of an android App I`m working on:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final int SCHEMA = 3;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE VISITAS (" +
"Id_Visita INTEGER PRIMARY KEY AUTOINCREMENT, " +
...
");");
}
...
}
Add some more details on what kind of problem or doubt are you having.
Post a Comment for "Put Database Into Android Project"