Retrieving the null value from Sqlite database in android - java

Guys i have stored a null value in the column of sqlite database
the value that is storing is return "null"
Now using following code to retrieve it
int i = resultSet.getInt(resultSet.getColumnIndex(columnName));
String str = resultSet.getString(resultSet.getColumnIndex(columnName));
boolean bool = resultSet.isNull(resultSet.getColumnIndex(columnName));
if( str == null ) {
return -1;
}
return i;
The debugger shows the value of str = "null"
but this condition is not working with str == null , str == "" , str == "null"
anyone can give me a hit of what to do..
Also resultset.isNull gives me a value of false.
So how can i store null in database, secondly if i use "null" then how can i make this condition work.

If you have stored the "null" literal string in the database, you compare against it like so --
if ( "null".equals(str) )
To store a null value in your database table, you use PreparedStatement.setNull()

Also resultset.isNull gives me a value of false.
resultset.isNull will give true if your your value = null. But as you said your value = "null" , which is a String.
The debugger shows the value of str = "null"
but this condition is not working with str == null , str == "" , str == "null"
try comparing with str.equals("null")
mDb.execSQL(updateQuery, valVars); USING this and null as one of the arguments stored in valVar but it gives error of null pointer exception
As sepcified on http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html this method should be used to - Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
Please try using update(String table, ContentValues values, String whereClause, String[] whereArgs) or updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm). Also please cross verify that your field in db allows NULL(i.e. Not Null = 0)
hope this helps :)

Check for String length.like,
if(str.length == 0){
}

Related

Why I am getting NullPointerException in my ternary operator?

My ternary operator is throwing a NullPointerException even though I explicitly check if the value of my list is null. However, if I add parenthesis around the ternary operator, my code works.
Code without parenthesis (throwing the exception):
final List<String> listData = null;
System.out.println("Insert new data (Created Monitorings) : " +
listData != null ? listData.size() : 0);
Code with parenthesis (working fine):
final List<String> listData = null;
System.out.println("Insert new data (Created Monitorings) : " +
(listData != null ? listData.size() : 0));
Can somebody explain it how exactly it is working.
This is about precedence of operators: the String+ has a much higher precedence than following ternary operator.
Therefore your first snippet actually does this:
( "Insert new data (Created Monitorings) : " + listData ) != null
? listData.size() : 0
Meaning: you concat a string (with a null listData), and compare that against null. Obviously that concat'ed string isn't null. Thus you do call listData.size(). And that resembles to null.size() which leads to your NullPointerException.
You are comparing the wrong thing against null! In the second snippet the ( parenthesises ) ensure that the result of ternary operation gets added to your string.
in snippet one the value that is compared to null is "Insert new data (Created Monitorings) : " + listData
'+' has more precedence than '!='
Hence Snippet 1 translates to:
(("Insert new data (Created Monitorings) : " + listData) != null ? listData.size() : 0;
The expression is not null so it proceeds to listData.size(). But as it is null, it throws the exception.

app crashes with cursor.getInt()

I have this method:
public String givenCheckmark(String name, String date)
{
SQLiteDatabase db = Cache.openDatabase();
Cursor cursor = db.rawQuery("select value from checkmarks where timestamp ='"+date+"' and habit ='"+name+"'", null);
String habitValue = "";
cursor.moveToFirst();
if (!(cursor == null)) {
habitValue = Integer.toString(cursor.getInt(0));
}
cursor.close();
return habitValue;
}
for some reason if i delete the
habitValue = Integer.toString(cursor.getInt(0));
the app does not crash. so the problem must be in the cursor.getInt(0). The query returns only one line. I am guessing the cursor is not in the first line but...why??
The most likely reason is the item at index "0" is not an Integer. Another reason is the Cursor itself may be empty. Finally, you probably have to check if there is actually a value returned.
To address the first part, you need to use Cursor#getColumnIndex() to get the index of the column you're trying to retrieve. So if it's an "id" you want, then you would do:
int id = cursor.getInt(cursor.getColumnIndex("id"));
To address the second part, you need to ensure that there were results returned. To do that, you just check Cursor#getCount(). So:
boolean isEmpty = cursor.getCount() == 0;
Alternatively, the return value for Cursor#moveToFirst() will actually return false if the cursor is empty meaning you can retrieve values by using something like this:
if (cursor != null && cursor.moveToFirst()) {
// The cursor is not null and contains elements. Continue retrieving values.
}
For the third part, you can use Cursor#isNull() to check if there is a value at the given index. So something like this:
boolean doesNotHaveValue = cursor.isNull(cursor.getColumnIndex("id"));
Other problems I see here is you're checking if the cursor is null after you move it to the first index meaning that you'll get a NullPointerException regardless of wether or not the cursor was null. You're also closing the cursor regardless of whether or not it is null.

Compare with null, not working in java

I have been trying to compare with null in if condition but it's not working and always goes in Else. Following is the code,
String authEmail = cursor.getString(cursor.getColumnIndexOrThrow("AUTHOR_EMAIL"));
Log.i(gtag, "author email => " + authEmail);
if (authEmail == null ) {
Log.i(gtag, "in author check - IF NULL");
} else {
Log.i(gtag, "in author check - ELSE ");
}
Here cursor is the result of querying SQLite database and AUTHOR_EMAIL is name of column. Logcat shows author email as null but still it goes in ELSE. Following is the Logcat:
06-24 15:30:55.307: I/GCA-Abs-Con(1282): author email => foo#bar.de
06-24 15:30:55.307: I/GCA-Abs-Con(1282): in author check - ELSE
06-24 15:30:55.357: I/GCA-Abs-Con(1282): author email => null
06-24 15:30:55.357: I/GCA-Abs-Con(1282): in author check - ELSE
3rd line of logcat shows authorEmail is null but still it goes in else.
I tried authEmail.equals(null) as well, but that didn't work too.
How should I modify the if condition to check for null perfectly ?
Thanks in advance.
To check whether a database field has the SQL NULL value, use the cursor's isNull method:
int index = cursor.getColumnIndexOrThrow("AUTHOR_EMAIL");
if (cursor.isNull(index)) {
...
} else {
String authEmail = cursor.getString(index);
...
}
try this
if (authEmail.equals("null")) {
instead of
if (authEmail == null ) {
Used .equals() for string comparison
Do it like this:
if (authEmail == null || authEmail.equals("null")) {
...
}
This first checks whether the variable is null. If it's not, it checks whether string is the text null. Of course, it's better to trace why the string can contain the text null which looks unintentional.
Use this
if (authEmail == null || authEmail.equalsIgnoreCase("null")) {
// handle null case
} else {
// handle other case
}

Checking if condition for 'null'

I have a doubt regarding checking null condition.For eg :
if(some conditon)
value1= value; //value1 is string type
else
value1= "";
Similarly some 4 other string value has similar condition.
What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part.
i did it like this
if(value1 == null)
{
}
but the pgm control didnot entered the loop eventhough value1="".
then i tried
if(value1 ==""){
}
this also didnt worked.
Cant we check null and "" value as same??
can anyone help me??
If you want to check is a String is null, you use
if (s == null)
If you want to check if a string is the empty string, you use
if (s.equals(""))
or
if (s.length() == 0)
or
if (s.isEmpty())
An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.
To check both "is not null" and "is not empty" on a String, use the static
TextUtils.isEmpty(stringVariableToTest)
It looks like you want to check wether a String is empty or not.
if (string.isEmpty())
You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().
When you are working on String always use .equals.
equals() function is a method of Object class which should be overridden by programmer.
If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))
You can use:
we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)
if(("").equals(s))
prefer below.
String str;
if(str.length() > 0)
{
Log.d("log","str is not empty");
}
else
{
Log.d("log","str is empty");
}

How to detect if a long type is actually NULL?

We have a nullable (type long) column (named referral) in our MySQL database. We use hibernate for ORM.
I am trying to get the value of the column for a given member. Some are null, and if its not, its an id that points to another member whose is the referrer.
The problem is in the java code I am trying to detect if that member's column is null, if not, do something.
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
member.getReferral() returns the value (type long) of the referral column. Some of those columns are null and some are not.
The above code compiles fine, but I get a nullPointerException when I call the method on a user whose referral column is null.
How do I properly do a detection on this?
Thanks in advance!
Full Answer:
Thanks to #Marcelo for the best correct answer.
Here is the code in its final state:
Long referrerAffiliateId = member.getReferral();
if (referrerAffiliateId != null) {
//...
}
Assuming member.getReferral() returns a Long, use:
if (member.getReferral() != null)
In Hibernate, if you want to be able to detect nullability in a property, you must not use primitive types, because they will always have a default value 0 for longs.
The exception probably comes from Long.toString(), try checking the value before converting to a string:
Long ref = member.getReferral();
if (ref == null) {
// Do something...
} else {
String referrerAffiliateId = Long.toString(ref);
// ...
}
Change
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
To:
if (member.getReferral() != null){
String referrerAffiliateId = Long.toString(member.getReferral());
//do something
}
It's likely that you're getting the NullPointerException when you call Long.toString() with a null parameter.
use Below code:
Long ref = member.getReferral();
String referrerAffiliateId = null;
if(ref != null){
referrerAffiliateId = Long.toString(ref);
}

Categories