Querying a database in android - android

I have a table login2 in /data/data/sankalp.jain.shre/databases/loginfinal.db.
The database has been created correctly which i have verified myself using adb sqlite3 and querying the table.
Inserting from commandline works but using rawQuery,it seems data is not getting added(cant get it on commandline too).
private SankalpDB dbhandle; //SankalpDB extends SQLiteOpenHelper
private SQLiteDatabase sqdb;
..............
public void open() throws SQLException {
System.out.println("Opening"); //This also gets printed.
sqdb = dbhandle.getWritableDatabase();
}
public void addUser()
{ System.out.println("Adduser");
System.out.println(sqdb.getPath()); ///prints /data/data/sankalp.jain.shre/databases/loginfinal.db
sqdb.rawQuery("Insert into login2 values('ax13','Kate','password');", null);
sqdb.rawQuery("Insert into login2 values('cax56','Natalie','passswd');", null);
....
...
sqdb.close();
}
The logcat output is not giving any error either.What am I doing wrong here.??

Try and do the following:
Cursor c = sqdb.rawQuery("Insert into login2 values('ax13','Kate','password');", null);
c.moveToFirst();
c.close();

Maybe you can try with the extended form
sqdb.rawQuery("Insert into login2 (alias,user,password) values('ax13','Kate','password');", null);
where alias, user and password are the DB fields

Related

android sqlite - table data cannot be updated

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

How to update a record in SQLite with Android?

How to update a record in SQLite with Android?
Hello.
I write because I am unfortunately stuck in my project and I hope you can help me.
How do I update a record in a database?
For example in a contact database. In this database of contacts, the following keys are used: name, phone, email and address; my problem is when I need to modify a record, what must I do to modify a record.
I hope you can help me. Thanks in advance.
This is the SQLite code to update the registry:
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
}
This same code I have found on many websites, but my problem is how to call the code from the MainActivity with Java.
1- create an instance from ur database in the main activity:
DBhelper db = new DBhelper(this);
2- call open:
db.open();
3- set the update method:
db.updateContact(name,phone);
4- close the database connection:
db.close();
5- open and close function in ur database helper class:
public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
6- also you gotta define those as global variables:
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
my advice to you is not to depend on written code you gotta learn to write it ur self specially database creation and usage it is really important so here is a good tutorial for you, you could benefit from it: http://www.tutorialspoint.com/android/android_sqlite_database.htm.
Good luck

java.lang.illegalstateexception database not open android

When I am trying to insert to data base log cat shows an error like java.lang.illegalstateexception database not open android.
But I have opened the db using
db = SQLiteDatabase.openDatabase(DATABASE_PATH, null,
SQLiteDatabase.OPEN_READWRITE);
The error is not occurring frequently.Anybody know the reason for this?
Try it like this:
if (!db.isOpen()) {
db = getApplicationContext().openOrCreateDatabase(DATABASE_PATH, SQLiteDatabase.OPEN_READWRITE, null);
}
try
DatabaseHelper dataHelper;
SQLiteDatabase mDb;
public DbManager openDB() throws SQLException {
mDb = dataHelper.getWritableDatabase();
return this;
}
and call this method where your re writing your current code.
Try this code
public class DataBaseHelper extends SQLiteOpenHelper{
public SQLiteDatabase openDataBase() throws SQLException{
//Open the database
File dbFile = _myContext.getDatabasePath( DB_PATH + DB_NAME );
_myDataBase = SQLiteDatabase.openDatabase(dbFile.toString(), null, SQLiteDatabase.OPEN_READWRITE);
return _myDataBase;
}//end of openDataBase() method
}
maybe you are opening an opened Database. close your database every time your work is done.

Database unclosed cursor. Close it after insert method

Would you mind pointing out what's wrong with this peace of code. genresCursor contains "Application did not close the cursor or database object that was opened here" exception. How do I really close this cursor after inserting ?
Thanks.
UPD: It seems like there wasn't a problem at all. Even though it contains exception that's still possible to extract data. I must've been wrong in my real application and this exception led me to conclusion that's it had been the issue. Thanks everyone for participating.
public class DatabaseCursorActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HashMap<Integer, String> _dummy = new HashMap<Integer, String>();
OpenDatabaseHelper helper = new OpenDatabaseHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(OpenDatabaseHelper.GENRES_ID_KEY, 1);
values.put(OpenDatabaseHelper.GENRES_TITLE_KEY, "Test");
db.insert(OpenDatabaseHelper.GENRES_TABLE_NAME, null, values);
db.close();
helper.close();
db = helper.getReadableDatabase();
Cursor genresCursor = db.query(OpenDatabaseHelper.GENRES_TABLE_NAME, new String[]{OpenDatabaseHelper.GENRES_ID_KEY, OpenDatabaseHelper.GENRES_TITLE_KEY }, null, null, null, null, null);
int i = genresCursor.getColumnCount();
genresCursor.moveToFirst();
}
public class OpenDatabaseHelper extends SQLiteOpenHelper {
public static final String GENRES_TABLE_NAME = "genres";
public static final String GENRES_ID_KEY = "id";
public static final String GENRES_TITLE_KEY = "title";
public OpenDatabaseHelper(Context context) {
super(context, "ttt.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + GENRES_TABLE_NAME + "( id integer primary key not null, title text);" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
You are opening the database first and after inserting you closed the database and then opened again to read the value.
First thing you don't need to close and open it again.You can do all of your operation and can close it as you are still in same block of code.
After doing the operation with your genresCursor close it by by genresCursor.close() and then close your db.Hopefully it will be fine.
I do not understand why you insert this code:
db = helper.getReadableDatabase();
Cursor genresCursor = db.query(OpenDatabaseHelper.GENRES_TABLE_NAME, new String[]{OpenDatabaseHelper.GENRES_ID_KEY, OpenDatabaseHelper.GENRES_TITLE_KEY }, null, null, null, null, null);
int i = genresCursor.getColumnCount();
genresCursor.moveToFirst();
The problem is in this part of code. If you just want to close cursor then call genresCursor.close(). But from the architecture point of view I do not understand why you need this code.
The Best Practice to work with cursor and database is that you should open it and close it in the same block of code. When I use to insert rows into database I use to open it at start and then insert many column and close it just before returning.
In API before Honeycomb you wont get any log message and performance issue regarding unclosed cursor but API before Honeycomb has a Cursor not closed detector which will log message about cursor not being closed.
Edit:
Close Database within same block of code. Cursor can be closed as per the scenario but must be closed before Context Deletion.

Android Database Update Record not working?

I have created a database. And opened it :
public SQLiteDatabase open() {
String path = "/data/data/com.develop.assetcapture/databases/Asset_Directory";
db = SQLiteDatabase.openOrCreateDatabase(path, null);
return db;
}
I'm writing a user registration and what to enable them to reset their passwords.
I have no problem inserting new records or querying the database. However on my resetPassword(username,password) method I get an error message:
android.database.sqlite.DatabaseObjectNotClosedException:
Application did not close the cursor or database object that was opened here
Please help, I've been stuck on this for too long now.
When you query the database you usually receive a Cursor object. Here is an example:
public Cursor querySomething() {
final String whereClause = ...
final String[] params = ...
final Cursor c = this.getReadableDatabase().query(
Table.TABLE_NAME,
Table.allColumnNames(),
whereClause,
params, // parameters for where clause
null, // group
null, // having
null); // order
return c;
}
Using the cursor c you access the rows in the answer. When you have finished processing the answer you have to close the cursor object:
c.close();

Categories

Resources