Does " try-with-resources Statement" really work with android Cursor object?
Asked Answered
N

0

7

Since Java introduced this statement since 1.7, I adopted this rule to write my cursor-related statement like this:

try (Cursor cursor = context.getContentResolver().query(queryAccountUri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                entry.userId = cursor.getString(0);
                entry.account = cursor.getString(1);
                entry.phone = cursor.getString(2);
                entry.nickName = cursor.getString(3);
                entry.icon = cursor.getString(4);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

However,these days our testers kept informing me that this statement still caused memory-leak while running monkey tests, or even drained all memory if making a loop test to this method. All of the log files indicated that the cursor object is the murderer due to some NOT CLOSING issue. Accordingly I have to change my code to close the cursor object manually like this:

try {
            if (cursor.moveToFirst()) {
                entry.userId = cursor.getString(0);
                entry.account = cursor.getString(1);
                entry.phone = cursor.getString(2);
                entry.nickName = cursor.getString(3);
                entry.icon = cursor.getString(4);
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        } finally {
            try {
                cursor.close();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

I've looked up Java doc for this statement and now I'm wondering if this statement really work with general "close-able object" or those "Pure Java reader/writer related object" only?

Nebo answered 30/9, 2016 at 4:26 Comment(1)
Better if you could post leak log.Liqueur

© 2022 - 2024 — McMap. All rights reserved.