Unable to load Database from Asset Folder (Android Studio) - android

quick background - I have no real programming knowledge so think complete beginner!
I used the below guide to load a database from the assets folder and it worked fine
http://www.javahelps.com/2015/04/import-and-use-external-database-in.html.
I now want to adjust this slightly so it loads a different SQLite database which I have created using DB Browser for SQLite but it is throwing the following error:
Missing databases/Exercisesthree.db file (or .zip, .gz archive) in assets, or target folder not writable
I have placed the new database (Excercisesthree.db.zip) in the same assets folder as the database that works (I have also left the unzipped file there too (Excercisesthree.db).
I altered the DatabaseOpenHelper class to open the Excercisesthree.db instead of the other db (code below) but for some reason it doesnt work. I suspect its something to do with the format of the database as I've hardly changed the code
package com.example.mat.externaldatabasedemo;
/**
* Created by Mat on 24-Jan-17.
*/
// http://www.javahelps.com/2015/04/import-and-use-external-database-in.html
import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "Exercisesthree.db";
private static final int DATABASE_VERSION = 1;
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
Here's a link to the database file:
https://1drv.ms/u/s!AupGvbDoJdp9i26l9oO5CcCGf2I0
This is the location of the database files:
C:\Users\Mat\AndroidStudioProjects\ExternalDatabaseDemo\app\src\main\assets\databases

Ok I've sorted it and confirm it was nothing to do with the Database format. In the end I created a new project and followed the original guide but changed it to the new database.
I think what must of happened is I'd changed some part of the code somewhere along the way and it stopped working. When testing it however it appeared to be working because the original databse had already been loaded onto the emulator and so it masked the fact that the database was no longer loading from the assets folder.
I would have like to have found out exactly what part of the code was missing and stopping it to work to understand a little more and report back but dont think I'll have time

Related

Room inflates database with old data

I am trying to auto-populate a database on first app load. I am trying to 'inflate' the database from a local copy like so:
public static synchronized bDB getInstance(Context context) {
if(bDB == null) {
Log.v("Hello", "Inflating database.");
bDB = Room.databaseBuilder(context.getApplicationContext(), BDB.class, databaseName)
.createFromAsset("database/bdb.db")
.fallbackToDestructiveMigration()
.build();
}
return bDB;
}
I noticed an error in the initial file (data error, schema remains the same). I corrected it and updated the file 'bdb.db'. However, every time the database gets pre-populated, it always picks up the old, erroneous data. I have tried the following:
Cleared and invalidated all caches.
Cleaned and rebuilt.
Checked the database file a million times.
While the file in the assets folder is correct, where is it picking up the old data from ?
Any help is most welcome.
Based on the discussion in the comments, you seem to have been bitten by auto-backup. With Room, this more typically manifests with a "cannot verify data integrity" error due to schema changes — in your case, the schema was the same, but the data was different.
You can configure auto-backup, both in terms of disabling it (as you did, setting android:allowBackup to false) or controlling what files get backed up (using android:fullBackupContent). And, you can do this on a per-build variant basis, such as having different values for a debug or a release build:
For android:allowBackup, you should be able to point to a boolean resource, with different values in main and debug
For android:fullBackupContent, you can have different XML resources in main and debug with different rules

.How to copy files from project assets folder to device data folder in android studio?

I am trying to use SQLiteAssetHelper and it requires me to create database on PC and copy it to assets/databases/databasename.db. I do that, but when I check on the device, nor the database, nor the databases folder is there under my app's data folder.
I did this based on a video, and the guy there doesn't do anything else to make the copy work.
So, are the files supposed to be automatically copied over to device?
If not, how can I copy the files?
So, are the files supposed to be automatically copied over to device? If not, how can I copy the files?
Yes it will BUT only when an attempt is made to access the database. Just instantiating the class that extends SQLiteAssetHelper will not copy the database and thus if that is all you do then the database will not be visible.
The steps when using SQliteAssetHelper to take should be :-
Create your project.
Amend the build.gradle to include implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' in the dependencies section.
Create the assets folder and then the databases folder in the assets folder and
Copy the database file into the databases folder.
Create the Database Helper class that extends SQliteAssetHelper.
Instantiate the Database Helper
Access the database (this is when the database is copied).
If when doing step 5 you use, as an example (based upon the information in the question) :-
public class DatabaseHelper extends SQLiteAssetHelper {
public static final String DATABASENAME = "databasename.db"; //<<<<<<<<< MUST match file name in assets/databases
public static final int DATABASEVERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
this.getWritableDatabase(); //<<<<< will force database access and thus copy database from assets
}
}
Then when doing 6 (instantiating the database helper), then 7 is done because this.getWritableDatabase(); accesses (implicitly opens) the database.
e.g.
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHelper; //<<<<< declares the database helper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHelper = new DatabaseHelper(this); // instantiates the database helper
}
}
The procedure you're explaining requires root access to the app storage on the device which is impossible on a normal non-rooted device due to security considerations. For this, you need a rooted device OR you could use emulator in Android Studio, that's much easier and user friendly approach:
Open emulator from Android Studio -> Settings -> Memory -> Internal Storage -> Others
A pop-up window will open. Click explore. You will get access to your app's internal storage so you can manage the database folder as well.
P.S.: Also, you might just package your app with the database table you have, just as with any other file, simply place it under your src/main/assets folder and access from code in runtime. Code samples are available in this thread : Android - Copy assets to internal storage (suggested by #Ezaldeen sahb)

Creating Database from SD card using Android Jellybean

Can anyone can create a database from SD card using Jellybean API 18?
but i should call this path like /storage/sdcard1. there are some many tutorials but does not work. Actually im using SQLiteOpenHelper.Some people says that if you create database from SD card, you dont need SQLiteOpenHelper.
Solution: You just have to modify the constructor in order to change it's path:
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
MySQLiteOpenHelper(Context context) {
super(context, "/mnt/sdcard/mydb.db", null, 0);
}
}
You can also get the folder string path and change it accordingly as you require. Ex: "/storage/emulated/0/folder/mydb.db"
Don't forget to add Write and Read Storage Permissions.
Try it, Hope it's helpful.

SQLiteAssetHelper NullPointerException at getReadableDatabase()

Because #CommonsWare suggested (in the comments to this answer) using the Android SQLiteAssetHelper library, I decided not to use Using your own SQLite database in Android applications method (a popular SO answer) to copy my pre-populated database from my assets folder to the app database folder.
Following the Android SQLiteAssetHelper directions, I set up my project like this:
Since I am using gradle, my database was in src/main/assets/databases/test.db.zip.
I used the .zip extension because the directions said
Earlier versions of this library required the database asset to be
compressed within a ZIP archive. This is no longer a requirement, but
is still supported. Applications still targeting Gingerbread (API 10)
or lower should continue to provide a compressed archive to ensure
large database files are not corrupted during the packaging process.
and I want to support earlier versions of android.
My database class is similar to the following:
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "test.db.zip";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
Again, I used the .zip extension for the DATABASE_NAME value because the directions said
...you must provide...a SQLite database inside the databases folder
whose file name matches the database name you provide in code
(including the file extension, if any)
However, when I do SQLiteDatabase db = getReadableDatabase(); I get a NullPointerException. What is the problem?
These SO questions and answers are not the same issue:
NullPointerException with Android SQLiteAssetHelper
SQLiteAssetHelper:Couldn't open database for writing (will try read-only)
SQLiteAssetHelper NullPointerException only on some devices
I set up the question to make the answer somewhat obvious, but here it is:
Contrary to what the Android SQLiteAssetHelper directions make it sound like (at the time of this writing, anyway. hopefully they will clarity them in the future), the DATABASE_NAME value should not include the .zip extension. Change your code to
private static final String DATABASE_NAME = "test.db"; // no .zip extension
but keep src/main/assets/databases/test.db.zip as it is, and everything should work.

can we store our Sql lite database-phonegap android?

can we store our Sql lite database in the assets folder for the Phonegap project?
I have already implemented an android project.i want to use the same DB for the Phonegap project.
can i use it? or else what is the alternative and what is the procedure for it?
I have searched for the past 2 days .i did not get any proper answer?
You can include the sqlite db in the assets folder but on first run of the application you'll need to move it to the right directory so the webview can open the database. There is a plugin and description of how to do exactly this at:
http://gauravstomar.blogspot.ca/2011/08/prepopulate-sqlite-in-phonegap.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+GauravSTomarBootstrappingIntelligence+(Gaurav+S+Tomar+:+Bootstrapping+Intelligence)
Alternatively you could include your DB as a .sql file and execute the file the first time you start your app:
http://simonmacdonald.blogspot.ca/2011/12/on-fourth-day-of-phonegapping-creating.html
My current MyPhoneGapActivity looks like this
package com.rkadukar.database;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
public class MyPhoneGapActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
Where do I add the code to copy the db file from Assets folder to the data/data/... folder for my application.
As per my understanding once the database is copied I can then delete the file and use the native PhoneGap storage API to read my imported database but in that case why do we need this plugin https://github.com/brodyspark/PhoneGap-SQLitePlugin-Android
Can someone kindly detail the steps required to
Copy the database from the assets folder to the data/data/.. folder
Read the copied database and perform operations on it.

Categories

Resources