Structural search and replace: find unclosed Cursors

Hi!

I just wasted a few days because of an unclosed Cursor in my Android project.
I was wondering if it would be possible to use Idea's structural search and replace feature to find any occurences of this in my project.

Basically it should find any instance of Cursor where the method returns before calling close() on it. Except if the method returns the cursor, in which case it is the caller that should call close() on it.

Would that be possible in theory?

Thanks for your help!

4 comments
Comment actions Permalink

Isn't the right way to handle this to use some kind of automatic resouce management (ARM)? Relying on inspections (by any name) seems like poor solution.


Randall Schulz

0
Comment actions Permalink

Thanks for your answer.
Hmm. I'm not familiar with this technique.
But given that this is for an Android project (running on devices with limited resources), I think it is generally not a good idea to rely on too many frameworks/libraries/automatic things.
A static analysis way to do this would be good trade-off in this context.

--
BoD

0
Comment actions Permalink

Who said anything about a "framework." Use try / catch / finally. (If you can't use a better language like Scala...)


Randall Schulz

0
Comment actions Permalink

Oh ok.
Well that's exactly my point then! My question was, is there a way to check that the code is not forgetting the try/finally using the structural search and replace feature :).
For instance:
Cursor c = (some query)
(use the cursor)
return;   <= here the check would say that the cursor is never closed

The correct code being:
Cursor c = (some query)
try {
     (use the cursor)
     return;
} finally {
     if (c != null) c.close();
}

Thanks!

0

Please sign in to leave a comment.