I have an field in database that is null
When I retrieve it in a cursor it is null.
I can tell that from the
cursor.isNull(1) is true
So when I do cursor.getLong(1) it should throw an exception according to the documentation. but it actually retrieves 0 without and exception.
any ideas why?
If you take a look at the implementation of the method getLong() in MatrixCursor , you can see the following code:
#Override
public long getLong(int column) {
Object value = get(column);
if (value == null) return 0;
if (value instanceof Number) return ((Number) value).longValue();
return Long.parseLong(value.toString());
}
If the value is null, then 0 is returned.
Related
I want to get value from several variables for example user1, user2, user3, user4.
how to check if variables are empty otherwise get the value and ignore variables that empty.
how I achieve this?, and sorry for newbie question...
if I do this
if(user1 != null && user2!= null && user3 != null && user4 != null){
user1.getText(); // or v1 = user1.value();
user2.getText(); // or v2 = user2.value();
user3.getText(); // or v3 = user3.value();
user4.getText(); // or v4 = user4.value();
}
which I dont want to do that, I just want to get the variable which had value in it and save it in array
Try with the following code.
ArrayList<String> listItems=new ArrayList<String>();
if(user1!=null)
{
listItems.add(user1.getText());
}
if(user2!=null)
{
listItems.add(user2.getText());
}
if(user3!=null)
{
listItems.add(user3.getText());
}
if(user4!=null)
{
listItems.add(user4.getText());
}
String [] arrayData = listItems.toArray(new String[listItems.size()]);
Note:You can also use isEmpty() method instead of checking for not a null value.
You mean a null check?
Value v1;
Value v2;
if (user1 != null) {
v1 = user1.value();
}
if (user2 != null) {
v2 = user2.value();
}
...etc
If you are dealing with String values then you may want to check the empty or null using TextUtils.isEmpty(str) API
public static boolean isEmpty (CharSequence str) Returns true if the string is null or 0-length.
if(user1!=null && !TextUtils.isEmpty(user1.getText()){
//not empty or null
}
I have a ContentValues that I'm parsing for data. I just received a very strange crash report:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke
virtual method 'long java.lang.Long.longValue()' on a null object
reference
private void populateMeta(final ContentValues values)
{
if (values == null)
return;
Date d = new Date(values.getAsLong(Meta.Data.TIMESTAMP));
...
}
When I look in getAsLong I can't see how this could happen:
public Long getAsLong(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).longValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Long.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Long value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Long: " + value, e);
return null;
}
}
}
It should just be returning null if the field is null, no?
Update:
Tried a few things to recreate that stack trace and in the end this narrowed it down:
values = new ContentValues();
Long timestamp = values.getAsLong(Meta.Data.TIMESTAMP); // null, as expected
Date d2 = new Date(timestamp); // source of error
Now here's the interesting thing. Adding a watch on new Date(timestamp) throws
NullPointerException: cannot unbox null value
which makes sense. However, letting that same line execute normally in code yields:
Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
Which I'm guessing is the root cause of the unbox error. I grasp unboxing, but I'm no expert, so I'd love a better explanation for why the stack trace seems so odd (and finicky) for this error. Thanks!
I had the same error, worked around by checking if such key exists with containsKey().
values.containsKey(Meta.Data.TIMESTAMP)
I am suspecting usage of weakreference to database results. Not exactly sure. Just adding a workaround here for this strange error.
I have a cursorLoader which returns a cursor with this data:
0 {
email=bogdan#gmail.com
about=Party
}
1 {
email=bogdan1#gmail.com
about=Paaarty
}
2 {
email=bogdan2#gmail.com
about=activity 2
}
3 {
email=bogdan3#gmail.com
about=activity 3
}
4 {
email=bogdan4#gmail.com
about=activity 5
}
How can I save the emails in an ArrayList called emails and the about in an ArrayList called about. I've been trying different things with the cursor but most of the time I just get outOfBounds.
Edit: This is the line that prints it like that:
Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor));
If you want to do it your way maybe this method would help (provided that you supply two empty ArrayList) ?
private void populateLists(Cursor cursor, List<String> emails,
List<String> about) throws IllegalArgumentException {
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
emails.add(cursor.getString(cursor
.getColumnIndexOrThrow("email")));
about.add(cursor.getString(cursor
.getColumnIndexOrThrow("about")));
} while (cursor.moveToNext());
}
}
I use the following method, but every time i use it i got error.
I cant figure out why because i perfrom this checking
if(unWanted == null || unWanted[0] == null)
The error is in this code:
unWanted[0] == null
but if i do only
if(unWanted == null)
It doest not see unWaned as null.
Thank for helping :)
the error code:
05-12 06:24:41.293: E/AndroidRuntime(24373): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
My method:
public void checking(){
DataBaseMain data = new DataBaseMain(this);
data.open();
String[] unWanted = data.getAllUnwantedExercies();
data.close();
if(unWanted == null || unWanted[0] == null)
Toast.makeText(this, "good", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "bad", Toast.LENGTH_LONG).show();
The method to get the String array from my DB.
public String[] getAllUnwantedExercies() {
Cursor c = ourDatabase.query(true, TABLE_NAME, new String[] {COLUMN_NOT_ON_LIST_EXERCISE}, null, null, COLUMN_NOT_ON_LIST_EXERCISE, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_NOT_ON_LIST_EXERCISE);
if(c.getCount() < 1)
return null;
int f = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false)
f++;
}
String[] list = new String[f];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false){
list[j] = c.getString(dayExercise);
j++;
}
}
return list;
}
unWanted[0] == null
It's clear that your array has no values in it. Attempting to reference the first index of an array of length 0, as explained in your stack trace, is a run time error.
unWanted == null
This doesn't work because the array object itself is not null.
A work around
A simple solution here is, at the end of your function, check the length of the array. If it is 0, you know it has no values, and you can return null.
if(list.length == 0)
{
return null;
}
else
{
return list;
}
or more concisely:
return list.length == 0? null:list;
Then when you get your array back from your function, all you need to do is test to check if the array is null.
if(unWanted == null)
{
// Array is empty.
}
Maybe just change this line:
if(unWanted == null || unWanted[0] == null)
By this one:
if(unWanted.length <= 0)
unWanted[0] == null
Here you are trying to check the first position of your array is null or not. Instead of this check your array size is 0 or not.
if(unWanted.length==0){
// your code
}
I hope this will help you.
You need to check that the length is greater than 0. It is not null because you are returning a list albeit an empty list. So it isn't null but also doesn't have a length
unWanted is not null does not mean you can reference it is first element by using unWanter[0] because it might be an empty array.
I have created a database and i want to retrieve some data from the database by using the cursor by i always get this error
04-19 20:02:56.747: E/AndroidRuntime(301): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
04-19 20:02:56.747: E/AndroidRuntime(301): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
04-19 20:02:56.747: E/AndroidRuntime(301): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
04-19 20:02:56.747: E/AndroidRuntime(301): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
here is the code of the function
public double getlatitude(String[] i,int x) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_SQUAREID, KEY_SQUARELATITUDE, KEY_SQUARENAME,
KEY_SQUARELONGITUDE
};
Cursor c;
c=ourDatabase.query("squares", columns,"squarename=?",i, null, null, null);
String latitude = null;
if (c.moveToFirst()) {
latitude=c.getString(0);
}
double latitude_double=Double.parseDouble(latitude);
return latitude_double;
}
Try this
if(c.getCount() > 0) {
c.moveToFirst();
for(int i=0;i<c.getCount();i++) {
//do your logic here
}
}
The exception likely occurred because your cursor is empty (there may have been no match). To avoid this make sure that you check whether the cursor is empty or not, if it is empty then you should not try to access it. And if it is not empty, you should check the max row count and make sure that you don’t access to any row that is equal or higher than the max row count. See the code below:
if ( c != null && c.getCount() > 0 ) {
if (c.moveToFirst()) {
do {
// do something here
} while (c.moveToNext());
}
c.close();
}
I think the problem is here:
latitude=c.getString(0);
Change it to:
latitude = c.getString(c.getColumnIndex("column_name"));
and also dont forget to close your cursor before returning value by calling c.close();
Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail, if you want to avoid weird crashes in the future.
if( c != null ){
if( c.moveToFirst() ){
//Do your stuff
}
}
//After finishing always close the cursor.
c.close();