I m trying to understand a RecyclerView.Adapter implementation i need to use, where the dataset is a Cursor object.
But some of the logic is not clear to me with regard to closing a Cursor object and than setting it to a different value.
What exactly is happening in close()?
Is this O.K. ?
public void setCursor(Cursor cursor){
mCursor.unregisterContentObserver(mMyContentObserverr);
mCursor.close();
mCursor = cursor;
mCursor.registerContentObserver(mMyContentObserverr);
notifyDataSetChanged();
}
Or should i play safe like this:
public void setCursor(Cursor cursor){
Cursor oldCursor = mCursor;
oldCursor.unregisterContentObserver(mMyContentObserverr);
oldCursor.close();
mCursor = cursor;
mCursor.registerContentObserver(mMyContentObserverr);
notifyDataSetChanged();
}
What are the benefits of using oldCursor?
Is there any danger in closing and setting on the same Cursor object?
thank you
The two pieces of code you included are functionally equivalent. The line
Cursor oldCursor = mCursor;
creates a new Cursor
reference that points to the same object, that is, mCursor
and oldCursor
have the same location in memory. Since they're the same object, oldCursor.close()
is exactly the same as mCursor.close()
.
However, when you set mCursor
to cursor
, mCursor
no longer refers to the cursor that was closed; it now refers to the same object as cursor
. Any operations that you perform on the new mCursor
will not be affected by the old mCursor
in any way.
As for which version you should use, I personally would stick with the first version. However, if you feel the code is more clear by creating oldCursor
, by all means, go for it. It's exactly the same.