how to check if the column of a SQLite dabase is null - android

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.

Related

How to check data in SQLite if already exist update or else insert in android

I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.

Return a string if row id doesnt exist

Here i have method to get the status of a person based on its id_number/number from the table. If person number exist it will return its status like PENDING or ACCEPTED.
However it number does not exist it should return string of NONE instead. The code works only if number exist but it returns ArrayIndexOutOfBounds if number does not exist;
How can i prevent ArrayIndexOutOfBounds so that if the number does not exist it will return to a value of string NONE.
public String getStatus(int number) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, new Sting[] {KEY_NUMBER,
KEY_FULLNAME, KEY_STATUS}, KEY_NUMBER + "=?",
new String[] {String.valueOf(number)}, null, null, null, null);
if(cursor != null) {
cursor.moveToFirst();
String status = cursor.getString(cursor.getColumnIndex("remark");
return status;
}
}
i call the method something like this;
String text = db.getStatus(100);
if(text.equals(null){
Log.e("Null: ", "null");
} else
Log.e("exist", "exist");
if this number doesnt exist it will crash and logcat shows ArrayIndexOutOfBounds
You need to check if the Cursor has returned any rows. You can do this by checking cursor.getCount() > 0, or if you need to iterate through the Cursor you can do the following:
while (cursor.moveToNext()){
//Do your code
return "Something";
}
return "NONE";
public abstract boolean moveToFirst ()
Added in API level 1 Move the cursor to the first row.
This method will return false if the cursor is empty.
Returns whether the move succeeded.
You are not making use of the return value of moveToFirst()
BTW, It's better to return null than an explicit string valued "NONE" because the comparison with null is quicker. Your code should change as
if(cursor != null && cursor.moveToFirst())
String status = cursor.getString(cursor.getColumnIndex("remark");
return status;
}
return null;

Android - Checking value from an SQLite DB table

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 .

Sqlite kill app if table is empty while checking for exists row?

I am facing problem with Sqlite only if I want to check for row existence.
If table is empty then application should be killed and closed by android. I have tried to trace the problem but I couldn't find it , where is the problem in my code ?
This is the row check existence function in my Sql class:
public boolean clExists( String email )
{
Cursor cursor = database.rawQuery("select 1 from "+TABLE_client+" where "+cl_email+"="+email, null);
boolean exists = (cursor.getCount() > 0) ? true : false;
cursor.close();
return exists;
}
and this is where I execute the code ( jsinfo.getString("email") ) a email String return from Json array and its not empty
datasource.open();
if ( datasource.clExists(jsinfo.getString("email")))
{
Toast.makeText(Login.this, "exists "+jsinfo.getString("email"), Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(Login.this, "not exists "+jsinfo.getString("email"), Toast.LENGTH_LONG).show();
}
datasource.close();
You need literal between email
Cursor cursor = database.rawQuery("select 1 from "+TABLE_client
+" where "+cl_email+"='"+email+"'", null);

Android cursor returns garbage data even if database is having correct information

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.

Categories

Resources