android - How can I embed an SQLite database into an application? -
i think have basic understanding problem maybe someone's able :-)
i'm developing android application using eclipse , application make use of database (only reading database implemented). database contains around 4,000 entries i.e. creating , populating database via source code not option. have created database in advance records.
but how can "embed" database file application , access it? databse around 500 kb in file size. downloading remote server not option either not allowed.
thanks, robert
i solved problem by:
adding
file.dbproject/assets folder;writing next class:
public class linnaeusdatabase extends sqliteopenhelper{ private static string database_name = "dragonfly.db"; public final static string database_path = "/data/data/com.kan.linnaeus/databases/"; private static final int database_version = 1; private sqlitedatabase database; private final context dbcontext; public linnaeusdatabase(context context) { super(context, dbactivity.databasename, null, database_version); this.dbcontext = context; database_name = dbactivity.databasename; // checking database , open if exists if (checkdatabase()) { opendatabase(); } else { try { this.getreadabledatabase(); copydatabase(); this.close(); opendatabase(); } catch (ioexception e) { throw new error("error copying database"); } toast.maketext(context, "initial database created", toast.length_long).show(); } } private void copydatabase() throws ioexception{ inputstream myinput = dbcontext.getassets().open(database_name); string outfilename = database_path + database_name; outputstream myoutput = new fileoutputstream(outfilename); byte[] buffer = new byte[1024]; int length; while ((length = myinput.read(buffer))>0){ myoutput.write(buffer, 0, length); } myoutput.flush(); myoutput.close(); myinput.close(); } public void opendatabase() throws sqlexception { string dbpath = database_path + database_name; database = sqlitedatabase.opendatabase(dbpath, null, sqlitedatabase.open_readwrite); } private boolean checkdatabase() { sqlitedatabase checkdb = null; boolean exist = false; try { string dbpath = database_path + database_name; checkdb = sqlitedatabase.opendatabase(dbpath, null, sqlitedatabase.open_readonly); } catch (sqliteexception e) { log.v("db log", "database does't exist"); } if (checkdb != null) { exist = true; checkdb.close(); } return exist; } }
Comments
Post a Comment