I'm trying to read data from newly deleted SQLite db table row.
Basically my program will delete a row when a certain activity is loaded, and I want to check the value inside the row.
This is my get code :
public String getSlot() {
String slots = new String();
Cursor cursor = database.query(ChosenSlotDatabaseHandler.TABLE_CHOSEN_PARKING_SLOT,
chosenSlotColumn, null, null, null, null, null);
if( cursor.moveToFirst() ) {
slots = cursor.getString(0);
}
// make sure to close the cursor
cursor.close();
return slots;
}
I've used these codes to delete the value :
public static final String DELETE_SLOT = "DELETE FROM "
+ TABLE_CHOSEN_PARKING_SLOT + " WHERE "
+ "_ID = " + CHOSEN_ID + ";";
public void deleteSlotSQL()
{
database.execSQL(ChosenSlotDatabaseHandler.DELETE_SLOT);
}
And this is my condition to set a TextViewvalue :
if(slots == null)
{
chosenSlotView.setText("You have not parked");
}
else
{
chosenSlotView.setText("You are parked in : " + slots);
}
At first, I thought that once the only row is deleted, getSlot() would return null, but it seems that it's not null from this Log.d I ran :
if(slots != null)
{
Log.d("notnull","not null dude");
}else
{
Log.d("null","Yay null");
}
The log returns "not null dude"..
Any suggestion on how to get the slots value so I can set the TextView value??
your slots definitely not null because of this :
String slots = new String();
it should be
String slots = null;
Cursor cursor = database.query(ChosenSlotDatabaseHandler.TABLE_CHOSEN_PARKING_SLOT,
chosenSlotColumn, null, null, null, null, null);
if( cursor.moveToFirst() ) {
slots = cursor.getString(0);
}
// make sure to close the cursor
cursor.close();
return slots;
EDIT :
Nevermind that String slot = null,
Try using :
if(slots.isEmpty())
{
chosenSlotView.setText(notParked);
}
else
{
chosenSlotView.setText(isParked + slots);
}
First off all you should avoid using logs like "not null dude", you will find them funny and suggestive but after a while we won t be able to write clean and professional code.
My second advice is to use constants instead of hadcoded strings . Create a class Constants and add there strings
public static final String NOT_PARKED = "You have not parked"
My third advice is to take a look at ormlite http://logic-explained.blogspot.ro/2011/12/using-ormlite-in-android-projects.html
If the logs are ok , maybe there is a problem with textview . Try putting a text in textview before the condition to check if will get set . Check the layout file also .
Related
I use one in my sqlite database a config table. This has the following composition:
private static final String DATABASE_CONFIG_CREATE =
"CREATE TABLE " + TABLE_CONFIGS
+ "("
+ CONFIG_HIDDEN_CATEGORIES + " TEXT DEFAULT '1,2' NULL"
+ ");";
Later I try to access with the following code:
Cursor cursor = database.query(DatabaseHelper.TABLE_CONFIGS, new String[] {DatabaseHelper.CONFIG_HIDDEN_CATEGORIES}, null, null, null, null, null);
try {
cursor.moveToFirst();
int test = cursor.getCount();
String data = cursor.getString(0);
}
catch (Exception exception) {
But the line cursor.getString(0) throws the following exeption (variable test is 0):
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
when I run the following code, the column CONFIG_HIDDEN_CATEGORIES is displayed to me... what is wrong?
Cursor dbCursor = database.query(DatabaseHelper.TABLE_CONFIGS, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames(); // index 0 is the value of CONFIG_HIDDEN_CATEGORIES
It means that your Cursor is empty. You should wrap your actions to correct condition:
try {
if (cursor.moveToFirst()) {
String data = cursor.getString(cursor.getColumnIndex("columnName"));
// do your stuff
}
else {
// cursor is empty
}
}
...
Your actual code won't work correct because you just calling moveToFirst() method but you don't know (are not testing) if it'll return true or false.
Your code works correct only if Cursor is not empty. In second case it won't work.
Note: I recommend you to use getColumnIndex(<columnName>) method for getting column index due to its name. This method is safer and more human-readable.
I am implementing an SQLite database and I can not figure out why some column values are null. Here is where I am writing to my SQLiteDatabase(db). The ArrayList DEFINITELY has the list of vehicles and each vehicle DEFINITELY has the correct values in it(Vehicle ID, address, city, state....). The table inside of the database also has the columns that i constructed(I checked this as well).
For some reason when I am doing a call like cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CITY)) it is getting null but when I do the same call but to KEY_LAT, it works. (Vehicle ID, Lat and Lon work, but the others do not)..
public static void addVehicle(ArrayList<Vehicle> aList) {
Database.openWritable();
ContentValues values = new ContentValues();
for(Vehicle vehicle : aList){
values.put(KEY_VEHICLE_ID, vehicle.getvehicleID());
values.put(KEY_ADDRESS, vehicle.getaddress());
values.put(KEY_CITY, vehicle.getcity());
values.put(KEY_STATE, vehicle.getstate());
values.put(KEY_LAT, vehicle.getLat());
values.put(KEY_LON, vehicle.getLon());
db.insert(TABLE_VEHICLE, null, values);
}
}
Additional Information/Question This do loop is happening like hundreds of times and i feel like it should only be happening for the number of rows i have, which is 14(i have 14 vehicles in the database). This may be affecting something? But i suspect not. So why is this happening? :
String query = "SELECT * FROM " + DatabaseHandler.TABLE_VEHICLE;
Cursor cursor = Database.listOfVehiclesDesired(query);
String lat = "";
String lon = "";
String title = "";
String snippet = "";
if(cursor.moveToFirst()){
do {
lat = (cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_LAT)));
lon = (cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_LON)));
title = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_VEHICLE_ID)) + " " + cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_VEHICLE_NAME));
snippet = "City:" + cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CITY)) + ", State: " + cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_STATE));
addMarkers(new LatLng(lat, lon), true, R.drawable.cap, title, snippet);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
Superfluous(?) BACKGROUND INFROMATION: I am using a static class to access the SQLiteDatabase, also, this code of getting column index and such is in an AsyncTask.
how you close cursor if cursor is closed ?!!
you code :
if (cursor != null && !cursor.isClosed()) {
cursor.close();
try the code with just cursor.close();
i am not able to get a reliable result to tell if the collumn of a database is null or not. i tried using a query checking to see if the the column of the database returns null or a string value of "" but no matter what i do the result of my check returns a result that there is something stored in that column, even if it is empty.
to make sure it is empty i delete all the data from the app and uninstall it from the device. that way i know the database column is empty
is there a better way to check if a particular column is empty?
if a column has never been used before on a newly created database, what is in that column? is it null or is there something put in by the system as a placeholder?
displayAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textToShow.setText(DisplayAllFieldsObjectFromDB());
if (DisplayAllFieldsObjectFromDB() == null) {
Toast.makeText(DisplayTable.this, "TABLE NULL ", Toast.LENGTH_SHORT).show();
} else if (DisplayAllFieldsObjectFromDB() != null) {
Toast.makeText(DisplayTable.this, "TABLE HOLDS A VALUE ", Toast.LENGTH_SHORT).show();
} else if (DisplayAllFieldsObjectFromDB().equals("")) {
Toast.makeText(DisplayTable.this, "TABLE HOLDS EMPTY QUOTES VALUE ", Toast.LENGTH_SHORT).show();
}
}
});
code from the database table
// display all data from table
public String getAllFromDB() {
String tableString = "";
String result = "";
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, null,
null, null, null, null, null);
if (cursor != null) {
// cursor.moveToFirst(); // use only this for getting one row
while (cursor.moveToNext()) { // use only this for getting multiple rows
tableString = cursor.getString(cursor.getColumnIndex(TABLE_STRING));
result += tableString + "\n";
}
}
return result;
}
Read the documentation: the cursor object has an isNull function.
I have a connection listener which gives me Collection, I have to insert these set of Strings in database with the checks that is it already exist in DB or not if not exist then insert. This listener gets called most of the time when network connection gets ON from OFF state, due to instability in network this methods gets called frequently, at this time Cursor data where I have put WHERE condition is always failed and count for the cursor returns 0. I have checked that cursor/database is getting closed or not, it is and not throwing any exception. Tried with blocking threads as well but still in 3rd or 4th call of cursor gets garbage, I have extracted the .db file and checks its entry DB data is perfectly stored in it but still return query failed.
Actually I am using asmack API to login with XMPP account and get Rosters, for Roster we have to set listener which gives presenceChanged(),entriesUpdate() etc. while network connection on/off situation entriesUpdate() method gets called and here I am checking whether the entries already exist in the database or not if not then insert, here cursor return garbage values.
Please let me know what could be the reason of getting cursor corruption? Does Android is having such issues with Cursor?
Note: I am not using ContentProvider
Here is the code:
private synchronized ArrayList<Contact> updateDBForNewEntries(int connectionIndex, Hashtable<String, String> addresses){
if(connectionIndex == NONE || addresses == null || addresses.size() <= 0)
return null;
String to = getAccountUserName(connectionIndex);
if(to == null){
return null;
}
AddressBookDBAdapter dbHelper = new AddressBookDBAdapter(context);
dbHelper.open();
String contactLookupTableName, whereClause, idColumn;
if (connectionIndex == MAIN_INDEX) {
contactLookupTableName = AddressBookDBAdapter.TABLENAME_CONTACT_DETAILS;
idColumn = AddressBookDBAdapter.CONTACT_ID;
} else {
contactLookupTableName = AddressBookDBAdapter.TABLENAME_VCARD_LOOKUP;
idColumn = AddressBookDBAdapter.VCARD_ID;
}
ArrayList<Contact> addedContactsList = new ArrayList<Contact>();
Iterator<String> iterator = addresses.keySet().iterator();
to = Utils.trimStringWithSlash(to);
while (iterator.hasNext()) {
String mailId = Utils.trimStringWithSlash((iterator.next()).trim()).toLowerCase();
if(mailId == null || mailId.trim().length() <= 0)
continue;
//check TO and FROM conditions
if(to.equalsIgnoreCase(mailId)){
mailId = null;
continue;
}
Utils.debugLog("*******frm update Mail Id = " + mailId);
if (connectionIndex == MAIN_INDEX) {
contactLookupTableName = AddressBookDBAdapter.TABLENAME_CONTACT_DETAILS;
whereClause = AddressBookDBAdapter.DATA_TYPE + "='"+ CONTACT_DATATYPE.IM + "' AND "+ AddressBookDBAdapter.DATA + " = '" + mailId.toLowerCase() + "'";
SQLiteCursor detailCursor = dbHelper.query(contactLookupTableName,
new String[] { idColumn },
whereClause, null, null, null, null);
Utils.debugLog("**** detailed cursor = " + (detailCursor != null? detailCursor.getCount():null)+"; whereclause="+whereClause);
try{
if(detailCursor != null){
if (!detailCursor.isClosed() && detailCursor.moveToFirst()) {
String searchKey = detailCursor.getString(0);
Utils.debugLog("****** mail Id already exist here="+whereClause + ";"+searchKey);
//TODO: Perform update operation here
} else{
//Mail Id not exist in database so add it a a new entry
//TODO:: Perform insertion
}
}
if(detailCursor != null && !detailCursor.isClosed())
detailCursor.close();
}catch(Exception e){}
detailCursor = null;
}
mailId = null;
}
Utils.debugLog("*** While loop ends " );
dbHelper.close();
to = null;
return addedContactsList;
}
Thank you,
Regards,
Aparna
try {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
}
}
Try to use and increment cursor like this.
Not aware of Android having issues regarding Cursor.
Could you please post some code? Maybe you forgot to move your cursor to First, or your "WHERE" clause is missing something.
I have written method which should return string with data from select query, but it doesn't work perfectly as I would like, here is method:
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
return cursor2.toString();
}
it returns some kind of string but, it is not the thing I want [ the string it returns is something like "SQLite.database.#" etc
You're returning the internal name of the Cursor you got from the query, not any data from the query results.
You should use something like:
cursor2.moveToFirst(); // position the cursor at the first returned row
String col = cursor2.getString(the_index_of_the_column_you_want);
cursor2.close();
return col;
Make sure you test for errors though (there might be no rows returned at all), and read the Cursor API docs.
Rewrite your code as
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
//Write these codes
if(cursor2.moveToFirst()) {
cursor2.close(); //You should close your cursor
return cursor2.getString(0); //index of your kolumna field
} else {
cursor2.close(); //You should close your cursor
return null; //Return some error msg, to notify that data not found
}
}
You can use the code below. You may catch exception after the try block. Even if you don't, you're guaranteed that the close() on the cursor will be called! I also suggest to always use English names for your vars.
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
if (cursor2 != null && cursor2.moveToFirst()) {
try { //use try - finally to close the cursor in the finally block
int index_kolumna = cursor2.getColumnIndexOrThrow(kolumna);
String kolumna_val = cursor2.getString(index_kolumna);
} finally {
if (cursor2 != null && !cursor2.isClosed()) {
cursor2.close();
}
}
}