Query SQLite Database on External Storage with Android App - android

I need to write an Android app that can query a SQLite database that is stored on a device's external storage, but I cannot figure out how despite everything I have looked at online, most of which was on StackOverflow. Here's the constructor for the class that I want to use to work with the database. I believe that this piece of code is sufficient information for my question, but if it is not, I can provide more.
public KetaiSQLite(PApplet p, String dbName, int dbVersion, String dataRootDir)
{
this.context = p.getActivity().getApplicationContext();
DATABASE_NAME = dbName;
DATABASE_VERSION = dbVersion;
DATA_ROOT_DIRECTORY = dataRootDir;
OpenHelper openHelper = new OpenHelper(this.context, dbName);
this.db = openHelper.getWritableDatabase();
}
How can I modify this so that I can query from a database on external storage? At the moment, db.getPath() returns /data/data/processing.test.app/databases/appData.sqlite.

SQLiteOpenHelper handles database creation and version management.
But you don't want that, so just use the openDatabase() function directly.

Related

SQLite file from assets not getting updated after inserting a record

I am trying to insert a record in my database but it's not updating my database.
My insert method:
public void insert(String name, String status, String seat, String id, String pnr) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_ID, id);
contentValues.put(DatabaseHelper.COL_NAME, name);
contentValues.put(DatabaseHelper.COL_PNR, pnr);
contentValues.put(DatabaseHelper.COL_STATUS, status);
contentValues.put(DatabaseHelper.COL_SEAT_NO, seat);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
Code when inserting:
dbManager = new DBManager(getContext());
dbManager.open();
dbManager.insert("Name","XYZ","B1 21", "2","2348384");
open method:
public DBManager open() throws SQLException {
databaseHelper = new DatabaseHelper(context) {};
database = databaseHelper.getWritableDatabase();
return this;
}
I am using SQLite Asset Helper in my DatabaseHelper and the database is stored in assests/databases
Thank you in advance!
Assets folder is meant for read-only purposes. You cannot alter the contents at run time - except build/development time.
In your case, I would suggest you to copy the database file from assets to your app's private folder (or your desired location) on SD/external storage and then use that database file to perform read/write operations.
In short, your assets' database is good for read operations only.
Note: same rules applies to Raw resources too and they serve a slightly different purpose.

android:copy sqlite database to device manually

I have developed an android app which will run just on one device,and i have an SQLite DB and i want to copy that in //data/data//databases directory on device internal storage,but i have two problems:
This directory for my app is not visible for me, while files of some other apps are visible.
I created this directory manually and copied the DB there, but it didn't work.
In emulator i copied db to the files that was created automatically and app works properly.
thanks for your helps
and this is my sqlite code:
SQLiteDatabase db=openOrCreateDatabase("a",MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT * FROM person WHERE id=?", new String [] {String.valueOf(1)});
c.moveToFirst();
String name=c.getString(c.getColumnIndex("name"));
db.close();
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(name);
You have to copy your SQLite database in assets folder, which is inside the main project folder. You cannot place it directly inside the /data/data/your application package/.
Follow this tutorial to get going on this.
There is a line in code,
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
replace this with
private static String DB_PATH;
and
update the constructor to
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
// you will get a warning if you'll try to hardcode your path
DB_PATH = myContext.getDatabasePath(DB_NAME).getPath();
}
rest is all explained in this tutorial.

Including an existing database in apk

I have an existing database with some data (something like a dictionary) and I want to put it in installation apk-package, I'll explain - I just want to use my existing database when the app is installed. Which is the best way to do it?
Put a database in res/raw/ and then copy it on the SD card when the app is first launched.
Create a SQL script which will create a database structure and fill the data and execute it in a db-helper class. I think it is a very bad idea, because I have about 1 million records from all tables and it will be hard to work with that script.
Use a static non-writable database like in this post
Anything else?
I would suggest you use the SQLiteAssetHelper library (https://github.com/jgilfelt/android-sqlite-asset-helper). It's an Android helper class to manage database creation and version management using an application's raw asset files.
This class provides developers with a simple way to ship their Android app with an already existing SQLite database (which may be pre-populated with data) and to manage it's initial creation and any upgrades required with subsequent version releases.
Your preloaded SQLite database will be stored in a zipped file in the assets folder and the SQLiteAssetHelper .jar library will be stored in your lib folder, make sure that you add it into your build path.
Then you can create a class with the folllowing:
A sample class that loads a pre-loaded database of title of songs and its title:
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseManager {
// DECLARATION OF ALL THE VARIABLES AND CONSTANT THAT WILL BE USED TO CREATE THE TABLE
private static final String DATABASE_NAME = "SongDatabase";
private static final String DATABASE_TABLE = "Song";
// DECLARATION OF ALL THE COLUMN REQUIRED TO BE CREATED
public static final String KEY_ROWID = "_id";
public static final String KEY_AUTHOR = "author";
public static final String KEY_TITLE = "title";
private DatabaseHelper mDbHelper;
private SQLiteDatabase ourDatabase;
private final Context ourContext;
public class DatabaseHelper extends SQLiteAssetHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
public DatabaseManager(Context context){
ourContext = context;
}
// open the database for access
public DatabaseManager open() throws SQLException {
mDbHelper = new DatabaseHelper(ourContext);
ourDatabase = mDbHelper.getWritableDatabase();
return this;
}
// Enter Values into the database or create database values
public long createRecords(String author, String title) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_TITLE, title);
return ourDatabase.insert(DATABASE_TABLE, null, initialValues);
}
// close the database after creating the values for security purposes
public void close() {
mDbHelper.close();
}
}
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
with this you can store data in your assets folder and copy it to you apk database
the problem is there is a limit to file size ie 10MB and you can not delete the data cos asset folder is read only so you will have duplicates and increase the apk size
https://github.com/jgilfelt/android-sqlite-asset-helper
the other option is you use it directly
good luck :)
#Whizzzkey at your request here is the answer :)
put the database in the assets folder, though you may not perform write operations from it, and for that you would have to copy the db to the sdcard (which is expensive) or to memory.
Happy coding.

External Database access in Android

Can I talk to the database of another application from inside my code?
Only, If that database is not a private to that application. (Also if your device is rooted then you can access any application's database) Also if that database is like a content Provider then you can access other application's database in your application. Like Android native phonebook database. (As it used their database as a content Provider.)
No, You can not.
same question
But you can try it by rooting the phone
link >> link
Reading DB from SDCARD>>
see the location of DB file then create a method inside a class, the method is like:
public class DB_Path {
public final SQLiteDatabase getDB() {
File dbfile = new File("path of file like : /sdcard/TheDataBaseFile");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
return db;
}
}
initialize like
public DB_Path dbp = new DB_Path();
public SQLiteDatabase db = dbp.getDB();
after that you can call the cursor with db.
Cursor cur = db.rawQuery("the sql query",null);
Reference link >> link
How to get table names from database >> link

Open sqlite database failed

I put my sqlite database file in the "assets" folder And i write a DAO calss to get data from database,But the information from log.e means i can not open the database.
public class GetData {
private static String DB_PATH = "/data/data/com.SGMalls/databases/mallMapv2.sqlite";
private static SQLiteDatabase myDataBase;
public static ArrayList<Mall> getMall(){
ArrayList<Mall> mallArrayList=new ArrayList<Mall>();
String queryString="select id,title from malls order by title";
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,SQLiteDatabase.OPEN_READONLY);
Cursor cursor=myDataBase.rawQuery(queryString, null);
if(cursor!=null){
cursor.moveToFirst();
while(!cursor.isLast()){
Mall mall=new Mall();
mall.setMallid(cursor.getInt(0));
mall.setMallname(cursor.getString(1));
mallArrayList.add(mall);
cursor.moveToNext();
} }
myDataBase.close();
return mallArrayList;
}}
The assets/ folder has nothing to do with databases, directly. If you put a database in the assets/ folder, you need to copy it from the assets/ folder to where you want the database to reside in the actual filesystem.
Have a look at this link .
You will have to call first createDataBase() method. If createDataBase() runs successfully, you can check your /data/data/com.SGMalls/databases/mallMapv2.sqlite is really present.
If it exists already, it won't do any harm to it.
copyDataBase() should give you some explanations about how it does to copy from assets to ../databases/..

Categories

Resources