How to do database schema migrations in Android? - database

Is there a standard way to do database schema migrations on Android? For example, user installs newer version of my Android app but the new version needs to make updates to the database schema (and wiping the user's database and starting over is not an option!). So I need to run some ALTER statements and/or copy tables the first time my new version runs.

Yes SQLiteOpenHelper has support for migrating between different versions of DB schemas.
Upgrading is done by implementing
public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
And Rolling back to a previous version is also supported :
public abstract void onDowngrade (SQLiteDatabase db, int oldVersion, int newVersion)

With a little bit of thought, you can nearly automate a lot of the SQLiteOpenHelper methods. Have a look at this blog post http://www.greenmoonsoftware.com/2012/02/sqlite-schema-migration-in-android/
Update: I ran into some issues if the database updates take a while to complete. Have a look at this blog entry for an implementation that works for me. http://www.greenmoonsoftware.com/2012/05/android-developer-how-to-safely-update-the-application-database/

As of version 3.0 Flyway now supports database migrations on Android. It works with SQLite, but also with any other database you wish to use (local in-memory one, or a DB on the server for two-tier apps).
Migrations can be written in both SQL and Java.

All the above answers concerning SQLiteOpenHelper are correct, but they all contain a kind of antipattern - creating/modifying DB structure with Strings. It makes both development and maintenance more expensive. Sometimes a migration consists of many statements, some of them may be quite big. Writing them as Strings, without any syntax higlighting... well, for small structures it might work, but for some bigger ones it'd be a nightmare.
A better way to manage schema changes would be to keep each migration script in external file and make SQLiteOpenHelper's onUpgrade method execute them automatically, in the proper order. Here's an article covering this topic: http://www.vertabelo.com/blog/sqlite-on-android-handling-database-structure-changes. I hope this helps.

You can enhance default SQLiteOpenHelper with library Android-Migrator, that allow you to apply migrations from sql files in android assets folder.

I know this is an old one but I have developed an open source eclipse plugin that is a domain specific language (DSL written with XText) that allows you to specify a database as a list of migrations.
It generates your ContentProvider, SqliteOpenHelper and Contract for you, into an API that resembles an API like the Contacts API or Media API.
I have written a basic guide that helps you get started here http://robotoworks.com/mechanoid-plugin/mechanoid-db/
So far it supports create table, create view and alter table statements, I hope to fully implement Sqlite syntax where appropriate for this DSL.
Hope that helps and sorry for the spam! :)

yanchenko's answer is correct, however, you might want to take a look at Droid Migrate, which is a framework I wrote that makes extensive use of SQLiteOpenHelper to facilitate automatic SQLite migrations (much like how Rails does it).

I also wanted something like flyway what I used in my Spring projects, but for android it seems not easy to make it work, so I created a very basic class which basically does the same.
So just put the sql files to the assets folder here: assets/dbmigration/yourdatabasenamelowercase in the format vN.sql where N is the version number. Then from onUpgrade just call like this:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
new DbMigrationHelper().doMigrate(context, db, DATABASE_NAME, oldVersion, newVersion);
}
onCreate is basically the same, but with fixed version parameters: 0 and 1
And this doMigrate method executes all the scripts in between the fromVersion - toVersion range (excluding fromVersion) in the proper order. So if you call it with e.g. 2 and 5 it will execute the v3.sql then v4.sql and then v5.sql from the proper asset folder. Each script can contain multiple statements (they must be separated with semicolons) and the scripts can contain full line sql comments (started with --). I hope that it can be useful for someone :)
So the class:
/**
* This class helps getting sql resources from asset for migration and to split complex scripts to sql statements automatically.<br>
* To create assets folder: right click on app (Project view) > new > folder > Assets folder ... and just click finish now you have src/main/assets folder.
*/
public class DbMigrationHelper {
private static final String TAG = "DbMig";
public void doMigrate(Context context, SQLiteDatabase db, String dbName, int fromVersion, int toVersion){
Objects.requireNonNull(context,"Context can not be null");
Objects.requireNonNull(db, "Database can not be null");
Objects.requireNonNull(dbName,"Database name can not be null");
if(fromVersion > toVersion){
throw new RuntimeException("old version (" + fromVersion + ") > new version (" + toVersion + ")");
}
if(fromVersion == toVersion){
Log.d(TAG,"Old and New versions are the same: " + fromVersion + " no migration will be done");
return;
}
try {
for (int i = fromVersion + 1; i <= toVersion; i++){
Log.i(TAG,"Migrating to version " + i);
String script = inputStreamToString(context.getAssets().open("dbmigration/"+dbName.toLowerCase()+"/v"+i+".sql"));
executeScript(script, db);
Log.i(TAG,"Migration to v" +i+ " has done.");
}
Log.i(TAG,"Migration finished.");
} catch (Exception e) {
throw new RuntimeException("Migration script problem: "+e.getMessage(),e);
}
}
private void executeScript(String script, SQLiteDatabase db){
Objects.requireNonNull(script,"Script is null");
List<String> statements = splitSqlScriptToStatements(script);
for(String statement : statements){
Log.i(TAG, "Executing: "+statement);
db.execSQL(statement);
}
}
private String inputStreamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
try(BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8 ))){
String str;
while ((str = br.readLine()) != null) {
sb.append(str).append("\n");
}
return sb.toString();
}finally {
is.close();
}
}
/**
* Splits sql script to statements. Removes empty lines and FULL LINE comments (started with --).<br>
* <b>All statements must be terminated with ;</b>
* #param sqlScript the full script content
* #return Sql statements in the exact order they are in the script
*/
private List<String> splitSqlScriptToStatements(String sqlScript){
List<String> res = new LinkedList<>();
if (sqlScript == null) {
return res;
}
List<String> valuableLines = removeCommentedAndEmptyLines(splitToLines(sqlScript));
StringBuilder buffer = new StringBuilder("");
for(String line : valuableLines){
if(buffer.length()>0){
buffer.append(" ");
}
buffer.append(line.trim());
if(line.trim().endsWith(";")){
res.add(buffer.toString());
buffer = new StringBuilder("");
}
}
if(buffer.length()>0){
res.add(buffer.toString());
}
return res;
}
/**
* Splits the given full text by \n
* #param sql
* #return not null list of lines
*/
private List<String> splitToLines(String sql){
List<String> res = new LinkedList<>();
if(sql == null){
return res;
}
return Arrays.asList(sql.split("\\r?\\n"));
}
/**
*
* #param src
* #return non empty list of lines containing no comments no empty lines
*/
private List<String> removeCommentedAndEmptyLines(List<String> src){
List<String> res = new LinkedList<>();
if(src == null){
return res;
}
for(String s : src){
if(s != null && !s.trim().startsWith("--") && !s.trim().isEmpty()){
res.add(s);
}
}
return res;
}
}

Related

Xamarin Forms - How do i use a Premade Local Database? [Solved] [duplicate]

I have started using the Xamarin plugin for Visual Studio to create an Android app.
I have a local SQL database, and I want to call it to display data. I don't see how I can do this. Is it possible?
After thinking this was a trivial thing to do, I was proven wrong when I tried setup a quick test project. This post will contain a full tutorial on setting up a DB for an Android App in Xamarin that will come in handy as a reference for future Xamarin users.
At a glance:
Add Sqlite.cs to your project.
Add your database file as an Asset.
Set your database file to build as an AndroidAsset.
Manually copy the database file out of your apk to another directory.
Open a database connetion using Sqlite.SqliteConnection.
Operate on the database using Sqlite.
Setting up a local database for a Xamarin Android project
1. Add Sqlite.cs to your project.
Start by going to this repository and downloading Sqlite.cs; this provides the Sqlite API that you can use to run queries against your db. Add the file to your project as a source file.
2. Add DB as asset.
Next, get your DB and copy it into the Assets directory of your Android project and then import it into your project so that it appears beneath the Assets folder within your solution:
I'm using the Chinook_Sqlite.sqlite database sample renamed to db.sqlite from this site throughout this example.
3. Set DB to build as AndroidAsset.
Right click on the DB file and set it to build action AndroidAsset. This will ensure that it is included into the assets directory of the APK.
4. Manually copy DB out of your APK.
As the DB is included as an Asset (packaged within the APK) you will need to extract it out.
You can do this with the following code:
string dbName = "db.sqlite";
string dbPath = Path.Combine (Android.OS.Environment.ExternalStorageDirectory.ToString (), dbName);
// Check if your DB has already been extracted.
if (!File.Exists(dbPath))
{
using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int len = 0;
while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write (buffer, 0, len);
}
}
}
}
This extracts the DB as a binary file from the APK and places it into the system external storage path. Realistically the DB can go wherever you want, I've just chosen to stick it here.
I also read that Android has a databases folder that will store databases directly; I couldn't get it to work so I've just ran with this method of using an existing DB.
5. Open DB Connection.
Now open a connection to the DB through the Sqlite.SqliteConnection class:
using (var conn = new SQLite.SQLiteConnection(dbPath))
{
// Do stuff here...
}
6. Operate on DB.
Lastly, as Sqlite.net is an ORM, you can operate on the database using your own data types:
public class Album
{
[PrimaryKey, AutoIncrement]
public int AlbumId { get; set; }
public string Title { get; set; }
public int ArtistId { get; set; }
}
// Other code...
using (var conn = new SQLite.SQLiteConnection(dbPath))
{
var cmd = new SQLite.SQLiteCommand (conn);
cmd.CommandText = "select * from Album";
var r = cmd.ExecuteQuery<Album> ();
Console.Write (r);
}
Summary
And that's how to add an existing Sqlite database to your Xamarin solution for Android! For more information check out the examples included with the Sqlite.net library, its unit tests and the examples in the Xamarin documentation.
Here is the one that I'm using and it's working
install the Sqlite plugin
create interface to access different platforms services
create a model for the table
implement the interface that you created earlier on all of the
platform you want to use
use the plugin to create, get, insert, etc on your table
for more detailed information check this

Windows Forms save to dataset but not table [duplicate]

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.
It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.
Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
You have several options to change this behavior. If your sdf file is part of the content of your project, this will affect how data is persisted. Remember that when you debug, all output of your project (including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
Answer Source
Here is a link to some further discussion and how to documentation.

Fetching all Microsoft Active Directory users in Domino Xpages NamePicker via java Agent

I'm working with LDAP Microsoft Active Directory and Domino server and quite new with this.
we've successfully fetched all Microsoft Active Directory users in Domino via java Agent and have printed all the user names in java debug console. For that referred this http://lotus-blogs.blogspot.in/2009/08/ldap-programming-using-domino-java-step.html link.
Now, i want to get all users in Domino Xpages NamePicker, so is this possible to get all users in Xpages NamePicker via java Agent?
As per we see that in Xpages NamePicker, we are able to fetch the Domino Users with the help of java beans.
Any kind of suggestion will be really Appreciated.
My java Agent is like following-
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
LDAPQuery.ldapconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
}
AND
import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
public class LDAPQuery {
public static void ldapconnect(){
String isFound="0";
try {
System.out.println("inside try 1");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "PROVIDER_URL");
env.put(Context.SECURITY_PRINCIPAL, "UserName");
env.put(Context.SECURITY_CREDENTIALS, "password");
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Specify the ids of the attributes to return
String[] attrIDs = {"cn","mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectCategory=person)(mail=*abc.com))";
System.out.println("filter defined");
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("", filter,ctls);
System.out.println("get the answer!");
try {
System.out.println("inside try2");
while (answer.hasMore())
{
SearchResult sr = (SearchResult)answer.next();
System.out.println("<<" + sr.getName()+">>");
Attributes attrs = sr.getAttributes();
//System.out.println(sr.getName().matches("/^[0-9]/"));
System.out.println(attrs.get("cn").get());
System.out.println(attrs.get("mail").get());
isFound="1";
}
if ( isFound=="1") {
System.out.println("User found in Active Directory!");
} else {
System.out.println("Opps ! User not found in Active Directory!");
}
answer.close();
}catch(PartialResultException e) {
System.out.println("catch 2");
e.printStackTrace();
}
// Close the context when we're done
ctx.close();
} catch (Exception e) {
System.out.println("catch 1");
e.printStackTrace();
}
}
public LDAPQuery() {
// Don't think I'm doing anything here
}
}
OK, got it.
Any particular reason why you are utilizing an Agent as opposed to using a true bean? Calling an agent everytime someone opens the name picker in my opinion is far from being effective.
Apart from that I don't see a way how the results from your agent could directly be passed into the name picker.
Third: looking at your ldap filter I'm sure that your code will return hundreds or even thousands of names. Using a standard ExtLib NamePicker is no fun for your users, believe me: the list of names displayed per dialog page is way too limited. But that may be a different story.
Sticking to the namePicker approach there are several ways how you could achieve what you appear to accomplish:
refactor your java agent into a javaBean then feed the result to the control
consider going for a directory syncing tool like IBM TDI; thus your AD data can be pushed into a Domino directory of your choice, and then from within your application you can utilize standard name lookup features

Logback dbAppender Custom SQL

Is there a way to change the tables that logback writes its data to using the dbAppender, It has three default tables that must be created before using dbAppender, but I want to customise it to write to one table of my choosing. Something similar to Log4J where I can specify the SQL that gets executed when inserting the log to the database.
Tomasz, maybe I'm missing something but I don't see how just using custom DBNameResolver could be the answer to what Magezy asked. DBNameResolver is used by DBAppender via SQLBuilder to construct 3 SQL insert querys - via DBNameResolve one can only affect names of tables and columns where data will be inserted, but can not limit inserting to just one table, not to mention that by just implementing DBNameResolver there are no means to control what actually gets inserted.
To match log4j's JDBCAppender IMO one has to extend logback's DBAppender, or DBAppenderBase, or maybe even implement completely new custom Appender.
The easiest way for me was to make an appender from scratch. I'm appending to a single table, using Spring JDBC. It works something like this:
public class MyAppender extends AppenderBase<ILoggingEvent>
{
private String _jndiLocation;
private JDBCTemplate _jt;
public void setJndiLocation(String jndiLocation)
{
_jndiLocation = jndiLocation;
}
#Override
public void start()
{
super.start();
if (_jndiLocation == null)
{
throw new IllegalStateException("Must have the JNDI location");
}
DataSource ds;
Context ctx;
try
{
ctx = new InitialContext();
Object obj = ctx.lookup(_jndiLocation);
ds= (DataSource) obj;
if (ds == null)
{
throw new IllegalStateException("Failed to obtain data source");
}
_jt = new JDBCTemplate(ds);
}
catch (Exception ex)
{
throw new IllegalStateException("Unable to obtain data source", ex);
}
}
#Override
protected void append(ILoggingEvent e)
{
// log to database here using my JDBCTemplate instance
}
}
I ran into trouble with SLF4J - the substitute logger error described here:
http://www.slf4j.org/codes.html#substituteLogger
This thread on multi-step configuration enabled me to work around that issue.
You need to implement ch.qos.logback.classic.db.names.DBNameResolver and use it in the configuration:
<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
<dbNameResolver class="com.example.MyDBNameResolver"/>
<!-- ... -->
</appender>
<appender name="CUSTOM_DB_APPENDER" class="com.....MyDbAppender">
<filter class="com......MyFilter"/>
<param name="jndiLocation" value="java:/comp/env/jdbc/....MyPath"/>
</appender>
And your java MyDbAppender should have a string jndiLocation with setter.
Now do a jndi lookup (see the solution answered in Oct 17 '11 at 16:03)

How to use my own sqlite database?

I put my database field in "assets" folder. And use the code from this blog to copy the database to "/data/data/my_packname/databases/", (This copy code i run it in the onCreate() method when i run this app) then use select * from ... to get data. But it gives me the exception: no such table.
Someone told me that if i am attempting to copy the file in SQLiteOpenHelper's onCreate(), it's too late. So the copy file code can not copy the complete file.
So i need to use adb or ddms to pull the database first?
So, Anyone can teach me how to use my own databse?
Can you tell me the setup?
I've used the instructions in that blog post and found them, while on the right track, to severely complicate the issue by unnecessarily extending SQLiteOpenHelper. I've had much better luck doing the following:
Create a utility class that creates the static db by copying it into the correct directory from assets, but doesn't get itself so hung up on following the SQLiteOpenHelper format.
Using the same utility class to open the db by using SQLiteDatabase.openDatabase()
Edit: Here is a version of this utility class I've created; it's not quite complete, but you'll get the drift.
public class DbUtils {
private static final String DB_PATH = "/data/data/com.mypackage.myapp/databases/";
private static final String DB_NAME = "my.db";
public static void createDatabaseIfNotExists(Context context) throws IOException {
boolean createDb = false;
File dbDir = new File(DB_PATH);
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbDir.exists()) {
dbDir.mkdir();
createDb = true;
}
else if (!dbFile.exists()) {
createDb = true;
}
else {
// Check that we have the latest version of the db
boolean doUpgrade = false;
// Insert your own logic here on whether to upgrade the db; I personally
// just store the db version # in a text file, but you can do whatever
// you want. I've tried MD5 hashing the db before, but that takes a while.
// If we are doing an upgrade, basically we just delete the db then
// flip the switch to create a new one
if (doUpgrade) {
dbFile.delete();
createDb = true;
}
}
if (createDb) {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(dbFile);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
}
public static SQLiteDatabase getStaticDb() {
return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
}
After you've copied the database, you should try closing and reopening the SQLiteDatabase object before executing any query on it. I had a similar problem with copying a db from an input stream and that's what solved it for me.
here is my Version from "Silvio Donnini" Code :),
now you can update the Database easily.
private static final String DB_PATH = "/data/data/pakagename/databases/";
private static final String DB_NAME = "databaseName";
private static SQLiteDatabase db;
public static void createDatabaseIfNotExists(Context context,int version) throws IOException {
boolean createDb = false;
File dbDir = new File(DB_PATH);
File dbFile = new File(DB_PATH + DB_NAME);
if (!dbDir.exists()) {
dbDir.mkdir();
createDb = true;
}
else if (!dbFile.exists()) {
createDb = true;
}
else {
// Check that we have the latest version of the db
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != version) {
dbFile.delete();
createDb = true;
}
}
if (createDb) {
// Open your local db as the input stream
InputStream myInput = context.getResources().openRawResource(R.raw.database);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(dbFile);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
SQLiteDatabase dbwrite = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
dbwrite.setVersion(version);
dbwrite.close();
if (db != null)
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
}
public static SQLiteDatabase getStaticDb() {
if (db != null)
return db;
return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READONLY);
}
I know this is an old question, but I lost a lot of time figuring it out, with the help of all the replies.
The issue is that a device stores a database in his data/data/.../databases folder. So, when you change sth about the database (name, add android metadata table, size..) it wont make any difference because of the stored database and the method that checked for existing database.
To get the newest database, after changing it, you must run the program without checking for existing databses (e.g. instead of dbExist = checkDataBase(); make it just false).
dbExist = checkDataBase();
Change to:
dbExists = false;
After you picked up the "new" databse you can return to checking the existing ones.
Hope it helps someone,
dina
I know this is an old post, but for those who still get here after a Google or a Bing search, this is the solution to the stated problem:
in createDataBase() there is the following check;
this.getReadableDatabase();
This checks if there is already a database with the provided name and if not creates an empty database such that it can be overwritten with the one in the assets folder. On newer devices this works flawlessly but there are some devices on which this doesn't work. Mainly older devices. I do not know exactly why, but it seems like the getReadableDatabase() function not only gets the database but also opens it. If you then copy the database from the assets folder over it, it still has the pointer to an empty database and you will get table does not exist errors.
So in order to make it work on all devices you should modify it to the following lines:
SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
db.close();
}
Even if the database is opened in the check, it is closed thereafter and it will not give you any more trouble.
Calm down guys,After long research finally found silly mistake for "no such table" error
Check name of database in Assets folder if it's like "DATABASE_NAME.EXTENSION" then put full name in Helper class with extension its solved my problem.
like say in Assets name of database is login.sqlite or login.db anything. put DB_NAME=login.sqlite fully with extention.
this tutorial now works perfectly.
The way of creating database from article you've posted is slightly diffrent from that how it's done in android examples (I don't want to say if it's good or bad).
I've learned how to use databases from SDKs NotePad sample
It's good example to start from, becouse it covers both database creation topic and database access through ContentProvider (it's really the only good way to get data from db, otherwise you will have problems when trying to get data simultaneusly from many places of your code).
You should note that SQLiteOpenHelper is really powerful and "it will help you" if you will use it properly. For example it stores current database version (not sqlite version but number you assingn with database schema version) and when you create new application version with new database structure you can update current schema to the new version in onUpdate.

Resources