I've been racking my brain on this for days and I just can't wrap my head around using SQLite databases in Android/Java. I'm trying to select two rows from a SQLite database into a ListArray (or two, one for each row. Not sure if that would be better or worse) and I just don't understand how to do it. I've tried various database manager classes that I've found but none of them do what I need and it seems that I should be able to do this simple task without the extra features I've seen in other database managers. Is there any simple way to JUST query some data from an existing SQLite database and get it into a ListArray so that I can work with it? I realize I need to copy the database from assets into the Android database path and I can handle that part. I also need to be able to modify one of the columns per row. I don't need to create databases or tables or rows. I implore someone to help me with this as I consider any code I've written (copied from the internet) to be completely useless.
You can create a method like this :
private List<MyItem> getAllItems()
List<MyItem> itemsList = new ArrayList<MyItem>();
Cursor cursor = null;
try {
//get all rows
cursor = mDatabase.query(MY_TABLE, null, null, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
MyItem c = new MyItem();
c.setId(cursor.getInt(ID_COLUMN));
c.setName(cursor.getString(NAME_COLUMN));
itemsList.add(c);
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
cursor.close();
}
return itemsList;
}
This will be inside your class let say MyDatabaseHelper where you will also have to declare a :
private static class DatabaseHelper extends SQLiteOpenHelper{
private final static String DATABASE_CREATE="create table " + MY_TABLE + " (id integer primary key, country string);";
public DatabaseHelper(Context context,String name, CursorFactory factory, int version){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion){
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS "+ MY_TABLE);
onCreate(db);
}
}
used to open() and close() the database.
Related
I already have a database in my app using a 3rd party library. The library doesn't seem to have drop table functionality. So I was thinking to directly change it using SQLiteOpenHelper API. Is this possible?
I have created a class that extends SQLiteOpenHelper and give it the same db name as the one used in the library.
public class SqliteDatabaseHelper extends SQLiteOpenHelper {
// Database Info
private static final String DATABASE_NAME = "myDatabase";
private static final int DATABASE_VERSION = 1;
private Context context;
public SqliteDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
L.w("old: " + oldVersion + ", " + "new: " + newVersion);
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + "deals_latest");
onCreate(db);
L.w("drop it like it's hot");
}
}
}
And I initialize it in Application class, just to see if it reflects the db class I created.
SQLiteDatabase db = new SqliteDatabaseHelper(this).getReadableDatabase();
L.w("version: " + db.getVersion());
L.w("path: " + db.getPath());
SqliteDatabaseHelper helper = new SqliteDatabaseHelper(this);
helper.onUpgrade(db, 1, 2); // this line suppose to invoke the drop table query
When running the app, onUpgrade() method doesn't seem to be called.
Mind you, I have never had any experience in using the native SQLite helper, so I have no idea what is going on here. My objective is just to see if the query in onUpgrade is executed or not. But the table still exists in the database.
How do I get around this?
The SQLiteOpenHelper class helps to manage versions of your own database.
It does not make sense to use it for a database that is managed by third-party code.
Just open the database directly with openDatabase().
I am having an existing sqlite database. I am developing an android app and I want to connect it with this existing sqlite DataBase.
Problem 1:
I have already included the sqlite database in my project via "DDMS push database function" as per my instructor's advise. Now I want to fetch the data from database, do I need to use SQLiteOpenHelper. If yes, how to use it and what will be coded in onCreate(SQLiteDatabase db) function and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) function as we already have the Database with us, we don't really need to create it.
Problem 2:
What should be done to simply fetch the required data from the existing database.
Being a newbie, I am quite confused, can someone please explain these concepts and guide me to overcome this issue. Any help would be appreciated.
I have seen a tutorial also for this purpose as sugggested by #TronicZomB, but according to this tutorial (http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/), I must be having all the tables with primary key field as _id.
I have 7 tables namely destinations, events, tour, tour_cat, tour_dest, android_metadata and sqlite_sequence. Out of all, only tour_dest is not fulfilling the conditions of having a primary key named as _id. How to figure out this one?
Following is the screenshot of table which is lacking the primary key field necessary for binding id fields of database tables.
The onCreate and onUpgrade methods will be empty since you already have the database. There is a great tutorial on how to achieve this here.
You could then access the database like such (example):
public ArrayList<String> getValues(String table) {
ArrayList<String> values = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT value FROM " + table, null);
if(cursor.moveToFirst()) {
do {
values.add(cursor.getString(cursor.getColumnIndex("value")));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return values;
}
Unless you are very comfortable with queries, databases, etc. I highly recommend you use http://satyan.github.io/sugar/ , it will also remove a lot of the boiler plate code required to do sqlite in Android
1. If DB already exists, onCreate will not invoke. onUpgrade will be invoked only if you will change DB version. onUpgrade you should to use if there some changes in your APP's database, and you have to make migration on new structure of data smoothly.
public class DbInit extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "name";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE = "create table connections . .. . ...
public DbInit(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (isChangeFromToVersion(1, 2, oldVersion, newVersion)) {
//Execute UPDATE here
}
}
private boolean isChangeFromToVersion(int from, int to, int oldVersion, int newVersion ) {
return (from == oldVersion && to == newVersion);
}
....
2. Simple example how to open connection to DB and get cursor object.
public class DAO {
private SQLiteDatabase database;
private DbInit dbHelper;
public ConnectionDAO(Context context) {
dbHelper = new DbInit(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public Connection getConnectionById(long id) {
Cursor cursor = null;
try {
open();
cursor = database.query(DbInit.TABLE_CONNECTIONS, allColumns, DbInit.COLUMN_ID + " = '" + id + "'", null, null, null, null);
if (!cursor.moveToFirst())
return null;
return cursorToConnection(cursor);
} finally {
if (cursor != null)
cursor.close();
close();
}
}
private Connection cursorToConnection(Cursor cursor) {
Connection connection = new Connection();
connection.setId(cursor.isNull(0) ? null : cursor.getInt(0));
connection.setName(cursor.isNull(1) ? null : cursor.getString(1));
.....
.....
return connection;
}
I am trying to insert some data into and SQLite DB on android, but the code below just does not work. Can anyone spot the issue.
db = this.openOrCreateDatabase("data_7.db", 0, null);
db.execSQL("CREATE TABLE IF NOT EXISTS 'group' (my_id TEXT NOT NULL, my_key TEXT NOT NULL)");
db.execSQL("INSERT INTO 'group' (my_id, my_key) VALUES ('abc', '123')");
db.close();
After running the code I extracted the SQLite file off the emulator and opened it using an SQLite GUI viewer, the table was created but no data was inserted.
Note:
I have searched through this site all day and could not find a
suitable answer to this issue
I would like to do this without the aid of helper methods like
.insert(). ie. I need to user pure SQL
Try out this way:
"INSERT INTO group (my_id, my_key) " + "VALUES ('" + field_one + "', '" + field_two + "')";
you have to create the table in the method onCreate() that is found on the Dababase class that you have to build like this:
public class Database extends SQLiteOpenHelper
{
public static final String DB_NAME="YourDBName";
public static final int VERSION=1;
Context context=null;
public Database(Context context)
{
super(context, DB_NAME, null, VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
try
{
String sql="CREATE TABLE group(my_id TEXT NOT NULL PRIMARY KEY, my_key TEXT NOT NULL)";
String insert="INSERT INTO group VALUES('abc','123');";
db.execSQL(sql);
db.execSQL(insert);
}
catch(Exception e)
{
Log.d("Exception", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS group");
onCreate(db);
}
}
Make sure that the old database is deleted or change the version to 2 in order to execute the query.
If you need to execute this query you need to write:
Database db=new Database();
SQLiteDatabasse read=db.getReadableDatabase();
I'm trying to to create a database and insert some data into it but this doesn't seem to be working. Can anybody tell me what's wrong in my implementation? Here is my code for the database. Thank you.
SQLiteDatabase db = null;
db.openOrCreateDatabase("order", null);
db.execSQL("CREATE TABLE IF NOT EXISTS order ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Price INTEGER)");
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', '100')");
SQLiteDatabase db = null;
db.openOrCreateDatabase.. will result in NullPointerException. You need to assign SQLLiteDatabase instance to db and then call openOrCreateDatabase on db.
Another issue is, 100 is integer, don't need in single quotes.
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', 100)");
There is a really nice tutorial supplied by google. It take you through how to do the basics with the SQLite database.
http://developer.android.com/resources/tutorials/notepad/index.html
I would suggest going through that.
In that tutorial is suggests using a SQLHelper inner class something like this
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE_CELEBS);
db.execSQL(DATABASE_CREATE_CHECKINS);
Log.i("dbCreate", "must have worked");
} catch (Exception e) {
Log.i("dbCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS celebs");
db.execSQL("DROP TABLE IF EXISTS checkins");
onCreate(db);
}
}
Then to get a new database you can call
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
You need to learn about SQLiteOpenHelper. Ask Google for some tutorials.
Incredibly Sqlite has much better performance "in transation" on inserts without transaction. I particularly, massive use transaction processes, or failure comes randomly at some point.
In example apps database is in most cases single table, so db schema is stored in static variable.
Storing large schema in seperate file is more friendly for me.
How can I do that? I thought about using resources (R.strings.db_schema) but probably there is a better way.
Could somebody give me any advice?
You could put the schema data in a raw file under res/raw. Then you can just load and parse that file the first time.
The way I do is to have a class per table, named after the table with "Table" suffix (e.g. PlayerTable or EventTable).
These classes contain all the static variable for the table name and all the field names, and they also contain two static methods:
public static void onCreate(SQLiteDatabase database)
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
So that my SQLiteOpenHelper can just call all of them, without having hundreds of static variables with all the fields and create queries. E.g:
#Override
public void onCreate(SQLiteDatabase database) {
PlayerTable.onCreate(database);
EventTables.onCreate(database);
..... any other table you have .....
}
This class is then injected into all my data access objects (select / update / insert queries). For them I have dedicated classes that contain all my methods, by functionality (e.g. EventHandlingDAO for all the queries that deal with event handling).
And finally, theses DAO are injected into the activities that need them, when needed.
EDIT: A few more details about my code:
My main objects are the DAO (data access objects), in which I have methods like:
// in EventHandlingDAO:
public void addEvent(Event event) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
try {
database.execSQL("INSERT INTO " + EventTable.EVENT_TABLE_NAME + " (...."); // list of fields and values
} finally {
database.close();
}
}
public List<Event> getAllEvents() {
final List<Event> result = new ArrayList<Event>();
SQLiteDatabase database = databaseHelper.getReadableDatabase();
try {
final Cursor cursor = database.rawQuery("SELECT " + EventTable.KEY_NAME + ", " + EventTable.KEY_DATE_AS_STRING + " FROM " + EventTable.TABLE_NAME, null);
cursor.moveToFirst();
// ... rest of the logic, that iterates over the cursor, creates Event objects from the cursor columns and add them to the result list
return result;
} finally {
database.close();
}
}
So in that DAO, I have my databaseHelper object, which instanciates my class that extends SQLiteOpenHelper with the methods I talked about above.
And of course, I have interfaces to all my DAO, so that I can inject a Stub or mocked implementation in my tests (or experiment with different implementations if I want to try another solution based on SharedPreference for example)
And the code for my PlayerTable table:
public static void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE); // TABLE_CREATE is my "CREATE TABLE..." query
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
// A bit blunt, that destroys the data unfortunately, I'll think about doing something more clever later ;)
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(database);
}