I am not able to query a pre-created database. I created a SQLite database using SQLiteDatabaseBrowser and I populated it. The following query works in the SQLiteDatabaseBrowser:
SELECT png FROM flags64 WHERE iso3='jpn' LIMIT 1
I moved the file in the folder "../assets/databases" in the android project into the Android Studio. This is the code used to query the database from my android app:
public class myStickerDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mysticker.db";
private static final int DATABASE_VERSION = 1;
public myStickerDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Bitmap getFlag(String iso3) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
Cursor c = db.rawQuery(String.format("SELECT png FROM flags64 WHERE iso3 = '%s' LIMIT 1", iso3), null);
c.moveToFirst();
byte[] png = c.getBlob(c.getColumnIndex("png"));
ByteArrayInputStream inputStream = new ByteArrayInputStream(png);
return BitmapFactory.decodeStream(inputStream);
}
}
Debugging the code the query does not return any records.
Update
It would seem that the database is not copied to the device.
The database size is about 250kb, but the copy in the device is about 24kb. Why?
Related
the table ( i.e. vaccines) structure is :
id- auto increment primary key
dose1_date - string
dose2_date - string
The DatabaseAccessor class is as follows. The initDB() and setVaccineDates methods are called from another activity. But the database is not updated. The logged message is found in the logcat however. The DatabaseHelper class is not shown here.
public class DatabaseAccessor {
public static DataBaseHelper myDbHelper = null;
public static SQLiteDatabase rdb = null;
public static SQLiteDatabase wdb = null;
public static synchronized final void initDB(Context context) throws Exception {
if (myDbHelper == null) {
myDbHelper = new DataBaseHelper(context);
myDbHelper.openDataBase();
rdb = myDbHelper.getReadableDatabase();
wdb = myDbHelper.getWritableDatabase();
}
}
public static void setVaccineDates(String birthDate) throws SQLException{
try {
String[] selections = null;
String qry = null;
qry = "select * from vaccines order by id";
Cursor cursor = wdb.rawQuery(qry, selections);
Log.d("update qry===== ", qry);
while (cursor.moveToNext()) {
int rowID = Integer.parseInt(cursor.getString(0));
ContentValues values = new ContentValues();
values.put("dose1_date","66666");
values.put("dose2_date","7777");
wdb.update("vaccines", values, "id=?", new String[] {String.valueOf(rowID)});
//wdb.close();
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}// end of method setVaccineDates
}
What to do ?
Edit : If I uncomment the wdb.close() line , I see in logcat
'06-09 04:21:05.387: W/System.err(4144): java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.cloudsoft.vaccine/databases/vaccines2.db
'
As a newbie in android it was just a mistake out of ignorance that this situation took place: after update operation I tried to find the changes in the database file (i.e. file with .db extension sitting inside assets folder in Eclipse) through sqlite browser . But what actually happens is the app running in the device (real one or emulator) has its own database which is created from the .db extension file inside assets folder and consequent database operations only affect the app's own database leaving no touch on the database inside the mentioned folder in Eclipse. And there is the way to watch the app's very own database in the running device in Eclipse's 'File Explorer' (in DDMS mode) with the help of Questoid SQlite Manager
I am working on pre-installed database and using SqliteAssetHelper library for that.
This is my db code
public class DBController extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "user.db";
private static final int DATABASE_VERSION = 1;
private final String TABLE_NAME = "User";
public DBController(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public ArrayList<UserData> getAllUserData() {
ArrayList<UserData> data_list = new ArrayList<>();
try {
// open database to query
SQLiteDatabase mySqliteDb = getWritableDatabase();
} catch (Exception e) {
Log.e("exception", "" + e);
}
close();
return data_list;
}
}
Error: Missing databases/user.db file (or .zip, .gz archive) in assets, or target folder not writable
and when I change my code to SQLiteDatabase mySqliteDb = getReadableDatabase(); I am getting android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database error.
I search for the problem and mostly everyon saying check your db present inside databases folder or not.
I tried using zip also still no luck. I guess I am missing something.
Your assets/ directory belongs inside main/, not inside app/.
Hi i have my own sqlite file and put in inside the assets folder it has multiple table inside. I want to query different table and display it in a listview. I've search different tutorial but it makes me confuse how will i call the different table? do i need to create a data model for each table and do i need to declare each table in my databasehelper? i always see's tutorial that you will create a database instead of using your own database. thank you
To use an existing database file(pre-populated with data), you can try Android SQLiteAssetHelper on github.
To prepare the database files, I recommand sqliteman
Create a database file in sqliteman, say "mydatabase", import the data. you can create multiple tables in a database file.
Put this file in assets/databases/ folder in your Android project.
Use this file with SQLiteAssetHelper
how will i call the different table?
You specify the table name in your SQL query, here is a very simple code, just for your references.
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mydatabase"; // This is the database file under assets/databases/ folder
private SQLiteDatabase readableDB;
private SQLiteDatabase writeableDB;
private static MyDatabase instance;
public static synchronized MyDatabase getInstance(Context context) {
if (instance == null) {
instance = new MyDatabase(context);
}
return instance;
}
private MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
readableDB = getReadableDatabase();
writeableDB = getWritableDatabase();
}
// Suppose tableA has two columns, name and id.
public ArrayList<String> selectNameById(String Id) {
ArrayList<String> result = new ArrayList<String>();
String query = "SELECT name FROM tableA WHERE id=?";
String[] whereArgs = new String[] { Id };
Cursor cursor = readableDB.rawQuery(query, whereArgs);
if (cursor.moveToFirst()) {
do {
Integer nameIndex = cursor.getColumnIndex("name");
String name = cursor.getString(nameIndex);
result.add(name);
} while (cursor.moveToNext());
}
return result;
}
}
I've used the GUI to create a DB which has 1650 records in it.
I'm trying to query this DB but it's always returning nothing. I've tried writing a simple getrowcount() method to see if I'm getting anything at all, but it always returns zero. I must be missing something obvious here, if someone can help point out what's going on.
In my main app.java:
db = new DbHandler(this);
String sIcao1 = "ROW COUNT = " + String.valueOf(db.getRowCount());
In my dbhandler.java:
package com.jammo.mywidget4;
<snip - standard includes>
public class DbHandler extends SQLiteOpenHelper {
private static SQLiteDatabase db;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "airports";
private static final String TABLE_AIRPORTS = "airports";
public DbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db = this.getWritableDatabase();
}
int getRowCount() {
int nCount = -1;
//SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM airports", null);
nCount = cur.getCount();
if (cur != null) {
//cur.moveToFirst();
//nCount = cur.getInt(0);
//if (cur.getInt (0) == 0) {
//}
}
return nCount;
}
}
In the GUI (SQLite DB Browser) I'm doing a simple
select * from airports
... and I'm getting back the full number of rows. When I debug the Java, cursor returns nothing.
Also, the DB created by the GUI is located in myapp/assets/airports.db.
Any ideas?
I think you need to include the .db in the DATABASE_NAME.
Try changing this:
private static final String DATABASE_NAME = "airports";
to this:
private static final String DATABASE_NAME = "airports.db";
Edit:
Actually I think even with this change it is not going to work for you. SQLiteOpenHelper is expecting your db file to be inside of /data/data/your.package/databases/ So I think you'll need to copy it from assets to there if you want it to work with an unmodified SQLiteOpenHelper.
See here to learn how to copy it over: Android: Accessing assets folder sqlite database file with .sqlite extension
HELP! Okay so I have been designing an android app for quite some time now and I have been manually putting all this data into strings and then just pulling them up in my layouts, but then a friend of mine suggested I put all the necessary data into a database and then just pull it out of there on each activity....sounds good....Accept I have been reading tutorial after tutorial on how this works and it seems much harder than just making lots and lots of strings and the examples in the tutorials each serve their own purpose which is not mine and dose not make understanding any easier for me. All I will be needing this database to do is read and display the info where I want it on the layouts. I created this database with SQLite Database Browser.
Database structure:
Name - fishindex_db
Tables - fish, states, reg
Rows:
fish - _id, name, desc, loc
states - _id, name, abbr, updated
reg - _id, name, size, season, quantity, notes
so now say I want to display all the content from primary key (_id) 12 from the reg table in a layout list view how is this done? need .java and .xml code example please.
These are two tutorials you can use to get you up and running in terms of what you want to achieve:
Android SQLite Database Tutorial
How to connect Android with PHP, MySQL - this one takes it a bit further in showing you how to connect to production databases and consume web services.
Hope this helps.
Take a look at the code to connect to fishindex_db
public class SQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "fishindex_db.db";
public static final String TABLE_NAME = "fish";
public static final String _id = "id";
public static final String name = "name";
public static final String desc = "desc";
private SQLiteDatabase database;
SQLiteHelper sQLiteHelper = new SQLiteHelper(MainActivity.this);
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//this is to get all records in fish table
public ArrayList<FishModel> getAllRecords() {
database = this.getReadableDatabase();
Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null);
ArrayList<FishModel> fishes= new ArrayList<FishModel>();
FishModel fishModel;
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
fishModel= new FishModel();
fishModel.setID(cursor.getString(0));
fishModel.setName(cursor.getString(1));
fishModel.setLastName(cursor.getString(2));
fishes.add(fishModel);
}
}
cursor.close();
database.close();
return contacts;
}