SQLite Database not working for android 5.1 - android

I have a simple SQLite database with a table having 2 columns, I just fetch data from the table using:
select * from myprofile;
This code works in pre 5.0 android properly, but doesnt work on 5.0 or 5.1 android.
Are there any changes to the normal select statement. I checked their documentation but couldnt find anything related to this
public void chkFirstTime()
{
SQLiteDatabase sampleDB1 = null;
Cursor c = null;
try {
sampleDB1 = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB1.execSQL("CREATE TABLE IF NOT EXISTS myprofile (username Text,useremail Text);" );
Log.w("table created", "table created");
c = sampleDB1.rawQuery("SELECT username,useremail FROM myprofile", null);
count= 0;
if (c != null ) {
if (c.moveToFirst()) {
do {
username1 = c.getString(c.getColumnIndex("username"));
Email1 = c.getString(c.getColumnIndex("useremail"));
count = count + 1;
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database1 in check_if_exists");
} finally {
if (sampleDB1 != null)
sampleDB1.close();
}
}

Related

Android cursor.getColumnNames() doesn't contain the new added column

I use code below to test if a column exists:
public static boolean isColumnExists(String tableName, String columnName) {
Cursor cursor = null;
try {
SQLiteDatabase db = getDatabase();
cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null);
String[] cloNames = cursor.getColumnNames();
if (cloNames != null) {
for (String temp : cloNames) {
if (columnName.equalsIgnoreCase(temp)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
The column hello2 doesn't exist in initial state, after adding column to database, the following test still tells that the column doesn't exist, and the second try will cause an error about duplicate column, which is not correct.
if (!isColumnExists("PositionCache", "hello2")) {
// First try will insert column to database
getDatabase().execSQL("alter table PositionCache add hello2 Integer default 0");
}
if (!isColumnExists("PositionCache", "hello2")) {
// Second try will give and error about duplicate column of hello2
getDatabase().execSQL("alter table PositionCache add hello2 Integer default 0");
}
I need to know the reason about such an abnormal phenomenon.
If I change SELECT * FROM to select * from in method isColumnExists then everything become normal.
I believe the reason is that SQLite (I strongly suspect the Cursor, so more correctly the Android SQLite aspect of the SDK) is cacheing data (perhaps because the underlying data is never retrieved from the Database as there is no need to get the data (as far as the Cursor is concerned)).
I've tried various checks including putting breakpoints in, checking the result of getColumnnames, and making the method non-static.
As soon as I add an alternative check using the PRAGMA table_info(*table_name*); then the column exists.
As such I'd suggest using the following :-
public static boolean isColumnExistsOld(String tableName, String columnName) {
Cursor csr = getDatabase().rawQuery("PRAGMA table_info(" + tableName + ")",null);
while(csr.moveToNext()) {
if (csr.getString(csr.getColumnIndex("name")).equalsIgnoreCase(columnName)) {
return true;
}
}
return false;
/*
Cursor cursor = null;
try {
SQLiteDatabase db = getDatabase();
cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);
cursor.moveToFirst();
String[] cloNames = cursor.getColumnNames();
if (cloNames != null) {
for (String temp : cloNames) {
if (columnName.equalsIgnoreCase(temp)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor && !cursor.isClosed()) {
cursor.close();
}
}
boolean rv = colfound;
return false;
*/
}
Note your code has been left in but commented out.
I believe that evaluating forces the cache to be refreshed (i.e. I tried this an yep it does dynamically change to include the column).

SQLITE DATABASE RESETS in ANDROID on application opening the second time,once the data is inserted

I m implementing sqlite db(database) for my android application.When i open my app i insert data into the database and the application exits.When i open the app second time and try to retrieve data i just inserted the app crashes after i click on button meant for retrieving data from database.Is the database reset everytime i open my app or their is some problem with the way i implemented database.
this is my code:
//For creating table:
private static String SAMPLE_TABLE_NAME = "PERSONS_TABLE";
private SQLiteDatabase sampleDB;
private void createTable()
{
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (COUNT INT(3),PERSON_NAME VARCHAR); ");
}
//Inserting
private void insertData()
{
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('"+c+"','"+pass+"');");
}
// For retrieving just the 1st column
public int cdata()
{
cursor = sampleDB.rawQuery("SELECT COUNT FROM " +
SAMPLE_TABLE_NAME, null);
if (cursor != null)
{
cursor.moveToFirst();
c=cursor.getInt(cursor.getColumnIndex("COUNT"));
cursor.close();
}
return c;
}
I m then using this c to set my textview to value in database using a button so that on button click ,i get to know whether their is any data in database w.r.t that column,but the second time i open the app.
So this time it crashes.
Code for store voice recognized word in database after user clicks on a button named 'yes'
//using this to store voice recognized word
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
// Populate the wordsList with the String values the recognition engine thought it heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
pass = matches.get(0);
Button yes = (Button) findViewById(R.id.button1);
yes.setOnClickListener(new View.OnClickListener(){
public void onClick(View view)
{
try
{
c=1;
sampleDB = openOrCreateDatabase("NAME", MODE_PRIVATE, null);
createTable();
insertData();
seeData();
}
catch (SQLiteException se)
{
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally
{
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
sampleDB.close();
}
}} );
private void seeData()
{
TextView txts=(TextView)findViewById(R.id.textView2);
cursor = sampleDB.rawQuery("SELECT COUNT,PERSON_NAME FROM " +
SAMPLE_TABLE_NAME, null);
if (cursor != null)
{
cursor.moveToFirst();
String personName = cursor.getString(cursor.getColumnIndex("PERSON_NAME"));
c=cursor.getInt(cursor.getColumnIndex("COUNT"));
//String country = cursor.getString(cursor.getColumnIndex("COUNTRY"));
//int age = cursor.getInt(cursor.getColumnIndex("AGE"));
txts.setText(personName);
if ( pass.equals(personName))
{
Toast.makeText(getApplicationContext(), "Device is unlocked", Toast.LENGTH_SHORT).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "WRONG PASSWORD", Toast.LENGTH_SHORT).show();
}
cursor.close();
}
}
Try it like this:
public int cdata()
{
cursor = sampleDB.rawQuery("SELECT COUNT(*) FROM " +
SAMPLE_TABLE_NAME, null);
if (cursor != null)
{
cursor.moveToFirst();
c=cursor.getInt(0);
cursor.close();
}
return c;
}

Unable to fetch data from sqlite database

In the below given program Iam inserting imei_number in the table .However I have to retrieve the inserted data and display it in different method.Please guide.thanks in advance
onCreate()
{
try {
imeiDB = this.openOrCreateDatabase(IMEI_DB_NAME, MODE_PRIVATE, null);
imeiDB.execSQL("CREATE TABLE IF NOT EXISTS " +
IMEI_TABLE_NAME +" (IMEI_number_db VARCHAR);");
imeiDB.execSQL("INSERT INTO " + IMEI_TABLE_NAME +" Values ("+IMEI_number_db+");");
Cursor c = imeiDB.rawQuery("SELECT IMEI_number_db FROM " + IMEI_TABLE_NAME , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
IMEI_number = c.getString(c.getColumnIndex("IMEI_number_db"));
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (imeiDB != null)
imeiDB.execSQL("DELETE FROM " + IMEI_TABLE_NAME);
imeiDB.close();
}
}
/****************/
fetch the data in another method
private collectdata()
{
String IMEI_number ="";
Cursor c = imeiDB.rawQuery("SELECT IMEI_number_db FROM " + IMEI_TABLE_NAME , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
IMEI_number = c.getString(c.getColumnIndexOrThrow("IMEI_number_db"));
}while (c.moveToNext());
}
}
}
The only one column do you search in the query is IMEI_number_db, so the cursor only has one column. You should change this:
IMEI_number = c.getString(c.getColumnIndex("IMEI_number_db"));
For this:
IMEI_number = c.getString(0);
You can also try the following code.
IMEI_number = c.getString(c.getColumnIndexOrThrow("IMEI_number_db"));

Handling Invalid SQLite Queries in Android

I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.
My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.
So far my method for searching looks like this:
public String search(DataBaseHelper myDB){
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
cursor.moveToFirst();
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
cursor.getString(cursor.getColumnIndex("Room"));
//Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
//msg.show();
cursor.close();
return data;
}
Cursor cursor = NULL ;
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
if(cursor != NULL)
{
try {
if (cursor.moveToNext()) {
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) +
" " + cursor.getString(cursor.getColumnIndex("Room"));
} else {
// Query result was empty, deal with it here.
}
} finally {
// Cursors should be closed
cursor.close();
}
}
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
//print exception
}
Cursor cursor = null;
String data = "";
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
// TODO: handle exception
}

Sqlite3 query not running properly on Android

I have a query like this
SELECT value1 FROM mytable where (value1 > value2) AND category = 1 ;
This is not executing properly in Android. Although if i manually go to
/data/data/packagename/databases/mydatabase.db
Here is the Code
try {
SQLiteDatabase sqdb = _context.openOrCreateDatabase(_DB_NAME, 0,
null);
String sql = null;
sql = "SELECT value1 FROM mytable where (value1 > value2) AND category = " + category
+"; ";
Cursor c = sqdb.rawQuery(sql, null);
Log.i("sql = ", sql);
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
categoryValue = c.getString(0);
c.moveToNext();
}
}
Log.i("categoryValue", categoryValue);
sqdb.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
And then execute it. Then it works perfectly fine.
What is happeneing?
i believe first you need to close cursor and then the database connection
//the order should be
c.close();
sqdb.close();

Categories

Resources