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.
Related
When querying the database directly, result is NULL, now Im using ResultSet to check if result is NULL, do something else, if result is not NULL, print the result: This my COde:
if(rs4 != null) {
while(rs4.next()) {
String ad =rs4.getString("number");
System.out.println(ad);
}
}
else{
System.out.println("ZERO ENTRIES");
}`
Database row value is NULL,since there is no row returned from my query so definitely i expect the else statement to run, but now the if statement is still being excecuted and prints null
What you see as NULL when querying the DB directly is the value of the column number, not the value of the row.
so, that's why you get a non-null row with a NULL value in number column in your ResultSet.
You can use something like:
if (!resultSet.isBeforeFirst() ) {
System.out.println("No data");
}
Or:
if (!resultSet.next() ) {
System.out.println("no data");
}
I finally found a way to go around it. Using rs.getInt() this will return 0 whenever row value is NULL and return new row value , whenever there is a row found.
This solved it :-)
while(rs.next())
{
// using rs.getInt() will return zero when row value from your query is NULL
int i = rs.getInt("number");
if(i<0) //check if zero
{
// When result is NULL i =0
System.out.println("your value");
}else{
//When there are rows found from database i > 0
String ad=rs.getString("number");
System.out.println(ad);
}
}`
This code gives me a Exception in thread "main" java.lang.NullPointerException. The exception occurs at the if statement at the bottom of the code.
public boolean printEmployees(Node Head){
boolean isSuccessful = true;
Node nodeChecker = new Node();
nodeChecker = Head;
int hospitalEmployeeCount = 0;
int doctorCount = 0;
int surgeonCount = 0;
int nurseCount = 0;
int administratorCount = 0;
int receptionistCount = 0;
int janitorCount = 0;
System.out.println(nodeChecker.getData().getRole());
while(nodeChecker != null){
if(nodeChecker.getData().getRole() == "h")
hospitalEmployeeCount++;
Another section of code reads data from a file and fills up a linked list. I have checked using break points and the linked list is there. nodeChecker points to the head of the linked list and when I call the System.out.println statement it prints h. I cannot figure out why the exception keeps happening.
Later on in this method I attempt to print to screen all of the information in the linked list. I have tried commenting out this section of code to test the remaining code, but it prints out as if the linked list is empty. I can check the variables in the linked list all the way up to the end of the function and it shows the data in the correct positions and the correct variables in the list.
nodeChecker is not null but nodeChecker.getData() is null, also String comparison is done incorrectly
Your while and ifstatements towards the bottom of your code need to be fixed.
Look at your while loop, it will stay looping as long as nodeChecker != null evaluates to true. However, nothing inside your loop changes its value, so it will always evaluate to true, which can lead to some problems.
At the bottom, in your "if" statement, there are four things which could possibly be null: nodeChecker, getData(), getRole(), or "h".
Since you are in the loop, we already know that nodeChecker is not null. "h" is trivially not null. If getRole() is null, there won't be an exception, because null == "h" will just evaluate to false.
Thus, by exclusion, getData() must be evaluating to null.
There are a few ways to get around this issue. One easy way is just adding an extra term in your if statement, as follows:
Data data = nodeChecker.getData();
if (data != null && data.getRole().equals("h")
What this is doing is taking advantage of http://en.wikipedia.org/wiki/Short-circuit_evaluation. Basically, if data == null, the LHS of the if statement will evaluate to false. Since it is an "and" statement, since the LHS is false, the statement cannot equal true, so the RHS will not bother to evaluate. If data != null, the LHS would then equal true, and the RHS will be evaluated. This protects from the null exception which comes from calling the getRole() method on a null object.
Also, make sure that you are using .equals() to check string equality, since "==" checks the equality of the references, while ".equals()" checks the equality of the value.
I am using Mongo DB With Java .
I am trying to find out if there exists a Symbol with the given String in the Mongo DB as shown below
This is working , but the problem is that it is making two calls to the MOngo DB , which is very expensive .
Is there any way i can reduce it to one call and make it more performance oriented .
This is my code
public class Test
{
public static void main(String args[])
{
DBCursor cursor = null;
DBCollection coll = null;
BasicDBObject query = new BasicDBObject();
String symbol = args[0];
query.put("symbol", "" + symbol);
cursor = coll.find(query);
int count = coll.find(query).count();
/* Here is want to avoid the count call , is there anyway by which
the cursor the obtained cursor tells , that there exists the symbol
in Mongo DB */
if(count>=1)
{
// If found then do
if (cursor != null) {
}
}
else
{
// If Not found then do
}
}
}
Why are you using count at all? You can just use the hasNext() method of DBCursor to test whether something is fetched or not.
cursor = coll.find(query);
if (cursor.hasNext()) {
// Found
System.out.println(cursor.next());
} else {
// Not found
}
However, if you want to use count() method, then also you don't have to fire a new query. Since db.collection.find() returns a DBCursor only. So, the count method you are using is on the returned DBCursor. So, just invoke count() on the same cursor reference: -
cursor = coll.find(query);
int count = cursor.count();
if (count >= 1) {
// Found
System.out.println(cursor.next());
} else {
// Not found
}
But, you should use the first approach, if you want to fetch the next element if present.
You do not need to make an explicit call to get the count.
cursor.hasNext() will return whether there is any element in the cursor or not.
cursor = coll.find(query);
while(cursor.hasNext()){
// found
}else{
// not found
}
You can also use cursor.count()
The count() method counts the number of documents referenced by a cursor.
Append the count() method to a find() query to return the number of matching documents, as in the following prototype:
db.collection.find().count()
or
db.collection.count()
This operation does not actually perform the find(); instead, the operation counts the results that would be returned by the find().
Reference
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){
}
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);
}