Showing posts with label adt. Show all posts
Showing posts with label adt. Show all posts

Wednesday, July 2, 2014

A little tip about equals() and hashCode()


Don't forget to check if equals() and hashCode() are overriden in any class (unless you use String or class that you're very familiar with) you use in collection!

And a little story about that...

Several days ago I tried to fix a memory leak somewhere in LruCache. LruCache provides a way to cache some objects while they're not exceeding a particular amount of memory. After that the oldest object in the cache is not being hold any more and available for garbage collector.

LruCache isn't a collection itself, but it should contain a map inside (and it does, have a look at the source code here) for key to value mapping (where the value is a cached object you need), so any class you use as key for LruCache should contain overridden equals() and hashCode().

But, unlucky for me, I used ResolveInfo as the key (and application icon as a value). Although it looks like a pretty simple data structure, it doesn't contain equals() and hashCode() overridden, I don't see the reason why - you can look here if you don't believe me.

So instead of caching it simply stored my icons and sometimes garbage collector couldn't do anything before OutOfMemoryError was throwed.

In my case, I replaced ResolveInfo to my own class that contains two fields: resolveInfo.activityInfo.packageName and resolveInfo.activityInfo.name and ultimately override equals() and hashCode(). Pair class is useful for such purposes too (and I actually copied equals() and hashCode() implementation from there) but it's always better to use more meaningful names.

Have a nice day!

P.S. Be careful to update to ADT 23.0.0 - it ruined my Eclipse and I needed to download the whole ADT Bundle for clean install. See here for details.

Wednesday, December 14, 2011

ADT 16

На днях ADT обновился до 16-й версии. Самое значительное изменение - появление Lint, утилиты, которая анализирует Android-проект и выявляет потенциальные баги, находит типичные ошибки раскладок (layouts), неиспользуемые ресурсы.

Раньше для поиска неиспользуемых ресурсов приходилось пользоваться сторонними утилитами (как, например, android-unused-resources), удобство пользования которыми, признаемся, оставляло желать лучшего. Я даже думал написать свою собственную утилиту (отчасти для себя, отчасти для того, чтобы получить плюс в карму за создание и поддержку полезного проекта с открытым исходным кодом :)), не взялся отчасти и от того, что ожидал чего-то подобного от Google, а инициатива от Google убила бы проект на корню. Дождался!

Полноценного анализа java-кода пока не производится, как и не производится анализ связей между проектами (например, ресурсы могут не использоваться внутри библиотечного проекта, но использоваться другими проектами в том же workspace), но, следует полагать, Lint будет только развиваться.

Всем удачного обновления и приятного дня!

Wednesday, October 19, 2011

Обновление ADT 14


ADT был обновлен до 14 версии, и сразу вылезла куча ошибок, связанных с использование R-ресурсов проекта-библиотеки.

Теперь R-файл библиотек содержит не константы, а обычные целые числа, что, в определенных случаях, позволяет избежать некоторых трудностей, как, например, переопределение какой-нибудь константы R.id и быстрее компилировать сложные проекты. Однако, использовать R.id в конструкциях switch-case не получится, т.к. в case обязаны лежать только константы. К счастью, Eclipse позволяет автоматически преобразовать switch-case в if-else по Ctrl+1 (Cmd+1 на маках).

Подробнее можно посмотреть здесь: http://tools.android.com/tips/non-constant-fields

UPD 21.10.2011. Если бы изменения касались только R-ресурсов :-( Навскидку за последние 48 часов, проблемы, с которыми столкнулся лично я:
http://groups.google.com/group/android-developers/browse_thread/thread/9findViewById93dc13262b84441/2c9d0f52e8a16bc1?lnk=raot
http://code.google.com/p/android/issues/detail?id=21031 (UPD 24.10.2011 - на эту проблему получен ответ от Tech Lead for the Android SDK at Google https://groups.google.com/group/adt-dev/msg/c1f4d73072f8b0e8)
UPD 27.10.2011. http://code.google.com/p/android/issues/detail?id=21162
http://code.google.com/p/android/issues/detail?id=21048
Так что обновляться пока никому посоветовать нельзя. А мне - урок, что незачем обновляться сразу после выхода обновления, а если обновляться, то аккуратно и с возможностью бысрого бэкапа.
UPD 28.10.2011. Вышел ADT 15, который должен исправлять многие проблемы. Попробую обновиться через пару дней.