- Android SDK Content Loader failing with NullPointerException
- 22 Answers 22
- java.lang.NullPointerException Can’t Find Source
- 1 Answer 1
- NullPointerException in Android device #176
- Comments
- sytolk commented Feb 25, 2016
- kroikie commented Feb 26, 2016
- yudhir commented Mar 28, 2016
- yudhir commented Mar 28, 2016
- mjhram commented Apr 18, 2016
- neocite commented May 16, 2016
- weicong96 commented May 23, 2016
- marcomorain commented Oct 14, 2016
- ogeidix commented Oct 23, 2016
- Sloy commented Oct 24, 2016 •
- Sloy commented Oct 24, 2016
- marcomorain commented Oct 24, 2016
- ogeidix commented Oct 24, 2016 •
- arsners commented Jun 26, 2017 •
- coyarzun89 commented Sep 7, 2017
- Bringoff commented Sep 15, 2017
- ogeidix commented Sep 18, 2017
- procedurallygenerated commented Nov 30, 2017
- anjalisingh commented Dec 1, 2017
- Robot2037 commented Dec 8, 2017 •
- henrikra commented Dec 13, 2017 •
- MattyK14 commented Jan 2, 2018
- henrikra commented Jan 2, 2018
- Как понять NullPointerException
Android SDK Content Loader failing with NullPointerException
I’ve just recently started getting an error any time I interact with the Android SDK and AVD Manager in Eclipse Helios
I’ve tried reinstalling the Eclipse plugin and the Android SDK but to no avail.
If I go to the «Installed packages» page and click refresh (or install or remove a package) I get a popup box saying that
Here is the full log:
Has anyone else encountered this recently? It doesn’t seem to be affecting actual Android development but its just kinda annoying.
22 Answers 22
The issue is in the your-avd-name.ini that is located at . \ \.android on your Windows machine (if you’re Windows user). When any error occurs during the avd.ini parser, the Google ADT plugin tries to access a map that is null. The workaround is to delete the offending .ini file and recreate your avd(s).
I solved the problem by deleting the .android directory in my user profile.
Step 1. Find the folder named: > .android
This folder can be located in your Windows user directory, for example in Windows 7/8:
Step 2. Delete this folder .android
Step 3. Restart Eclipse and it is OK now
I solved the problem by deleting the .metadata folder from workspace
/.avd and delete the .ini file of the AVD ..Restart Eclipse.. otherwise if you don’t know what file to delete or the above solution did not work for you, delete the entire created AVD folder..and restart eclipse..
The issue is in the your-avd-name.ini (config files) that is located at .android (search it)on your Windows machine (if you’re Windows user). When any error occurs during the avd.ini parser, the Google ADT plugin tries to access a map that is null. The workaround is to delete the offending .ini file and recreate your avd(s).
Try to delete .android folder from
and open your eclipse and follow this Structure to configure your SDK for either installing new SDK or from installed one
I believe the trouble was with your ADT tools. If you had run eclipse plugin updates (which would update ADT), problem would have solved.
I get this parseSdkContent failed problem sometimes when I select improper values for a virtual device, if that improper value results in a blue screen of death upon AVD launch: After the crash when the computer restarts the «parseSdkContent failed» error will come when starting Eclipse.
This will give you all sorts of errors that does NOT at all give you any clue to the problem, from all the errors you may be tempted to reinstall Eclipse or even Java, but dont do that, it could be much simpler.
The solution for me is pretty simple: delete your .avd folder and the .ini file in ..Users\.android folder.
Backing up your AVD is therefore a good idea since it becomes corrupted if it crashes with Besod during launch.
Источник
java.lang.NullPointerException Can’t Find Source
I’m in the process of programming a java rpg game, and have reached an impass. My code currently has sprite animation, a random map generation with perlin noise and collision detection. The map is tiled base, so i’m currently trying to convert the perlin noise to tiles. The perlin functions generate a array, and im each number of that array to a tile png. This is where the problem comes: RUNTIME ERROR: Java.Lang.NullPointerException. The probleme is my compiler (netbeans) does not show me where the error occurs, but instead only gives me this error code. With a process of exclusion I managed to locate the error, which occurs at line 364. If this site doesnt support lines, it is at the loadTile() method, at «if(perlinIsland[x][y] Follow
1 Answer 1
Your limited catch block code hampers your ability to find your nulls.
For instance, these lines of code:
Will only print
without line numbers or stack trace when this code runs into an NPE.
First off, you should not be trapping for plain Exception but rather for explicit Exceptions. Next you should use a more informative catch block, for instance one that at least prints out the stack trace via e.printStackTrace() .
The block above should really be written:
Do this, and you’ll see that the NPE occurs here:
Then you can stuff code in front of that line to see which variable is causing the problem:
And you’ll see the problem is that isSolid[x][y] is null:
And why is that? It’s an array of Booleans, not booleans, so it is not initialized to Boolean.FALSE but rather it defaults to null. Solution: either use boolean[][] array or initialize your array explicitly.
Most important: use informative catch blocks and don’t catch for general Exceptions.
Edit note that as an aside, in order for me to get your code to run, I had to disable your use of images and sprite sheets, since these are resources that are unavailable to me. This effort should be yours though since you are the one seeking in the future. I ask that in the future, you limit your code to the smallest code that we can test and run, that demonstrates your problem, but that has no code unrelated to your problem, and that does not rely on outside resources such as images, databases, etc. an sscce.
Источник
NullPointerException in Android device #176
Comments
sytolk commented Feb 25, 2016
The text was updated successfully, but these errors were encountered:
kroikie commented Feb 26, 2016
Could you provide some more context around your issue, eg: code snippet, how often you can reproduce the issue.
yudhir commented Mar 28, 2016
MAGIC PUSH
My Crashlytics show this similar error once but I haven’t sent any Push to any devices . The date registered for error on Crashlytics is Dec27 2015 even If the app launched a week ago.
The null pointer is shown to the String from. It is the default parameter for onMessageReceived. The device is some Rooted Android 4.1.1 GI I9500 TMMARS
yudhir commented Mar 28, 2016
Found the reason.
TMMARS appears to be software from Trend Micro.
Trend Micro Mobile App Reputation Service or TMMARS is a cloud-based service that automatically identifies mobile threats based on app behaviors.
It is extremely likely that the system is not behaving as the App expects it to, simply because it is a threat detection environment.
mjhram commented Apr 18, 2016
Hi,
I have the same issue.
How this can be solved?
neocite commented May 16, 2016
weicong96 commented May 23, 2016
I had the same issue, was resolved by removing code that starts the class that inherits the GcmListenerService explictly
marcomorain commented Oct 14, 2016
I’m hitting the same issue. It hit lots of times last night.
ogeidix commented Oct 23, 2016
Hi Marco,
which version of GCM are you using?
also, any chance you can update to Firebase Cloud Messaging?
Sloy commented Oct 24, 2016 •
We’re seeing exactly the same issue in crashlytics. I cannot seem to be able to reproduce it locally.
We were using the old BroadcastReceiver+IntentService technique, and we recently updated to GcmListenerService. That’s when these crashes started to appear.
We’re using version 8.4 of GCM, and cannot migrate to FCM at the moment.
Sloy commented Oct 24, 2016
From reading the obfuscated code of GcmListenerService, it looks like the NPE is caused by the action switch in the zzo(Intent) method, because the intent’s action is null. I can’t be sure, but it also seems like this is coming from the zzn(intent) method called from onStartCommand .
I wonder, how could an intent arrive with a null action? Is this a different scenario from a normal server push? Since this is executed inside a ThreadPool we lose sight of the stacktrace.
And more importantly, @ogeidix is there a way to work around this?
marcomorain commented Oct 24, 2016
This happening with com.google.android.gms:play-services-gcm:8.4.0. We have recently upgraded to 9.4.0 but I can’t verify if the problem occurs with that version.
ogeidix commented Oct 24, 2016 •
GCM 8.4 is quite old.
Please update to the latest version of GCM (FCM would be even better) and report back if the problem persists.
arsners commented Jun 26, 2017 •
Happened at 02/03/2017
java.lang.NullPointerException
at com.google.android.gms.gcm.GcmListenerService.zzm(Unknown Source)
at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source)
at com.google.android.gms.gcm.GcmListenerService$1.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
coyarzun89 commented Sep 7, 2017
I have the same issue. It happen only on Android 4.3. I’m using the version 11.0.1 of GCM.
Fatal Exception: java.lang.NullPointerException at com.google.android.gms.gcm.GcmListenerService.handleIntent(Unknown Source) at com.google.firebase.iid.zzc.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:841)
Bringoff commented Sep 15, 2017
@coyarzun89 got two crashes with identical stacktrace from rooted Nexus 5 with Android 4.3. Google services v11.2.0.
ogeidix commented Sep 18, 2017
Thanks @coyarzun89 @Bringoff for the update.
Will investigate and add more safeguards
procedurallygenerated commented Nov 30, 2017
@ogeidix Got a similar crash with play-services-gcm:11.4.0.
Device Nexus 5 with Android 4.3
anjalisingh commented Dec 1, 2017
@ogeidix same crash with play-services-gcm:11.4.0.
Rooted Device Nexus 5 with Android 4.3
Fatal Exception: java.lang.NullPointerException at com.google.android.gms.gcm.GcmListenerService.handleIntent(Unknown Source) at com.google.firebase.iid.zzc.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:841)
Robot2037 commented Dec 8, 2017 •
Same problem here, on rooted device though. Using Play Services 11.6.2.
henrikra commented Dec 13, 2017 •
We are getting this randomly at production too! Looks like it is only on OS version 4.3 and below for us. Looks like many people are having the same problem on 4.3 and below 🤔
MattyK14 commented Jan 2, 2018
Also seeing this error from a user on Android 4.3.
henrikra commented Jan 2, 2018
We ended up raising the minimumSdk to 19 so our app does not have Android users 4.3 or below 👼
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Как понять NullPointerException
Эта простая статья скорее для начинающих разработчиков Java, хотя я нередко вижу и опытных коллег, которые беспомощно глядят на stack trace, сообщающий о NullPointerException (сокращённо NPE), и не могут сделать никаких выводов без отладчика. Разумеется, до NPE своё приложение лучше не доводить: вам помогут null-аннотации, валидация входных параметров и другие способы. Но когда пациент уже болен, надо его лечить, а не капать на мозги, что он ходил зимой без шапки.
Итак, вы узнали, что ваше приложение упало с NPE, и у вас есть только stack trace. Возможно, вам прислал его клиент, или вы сами увидели его в логах. Давайте посмотрим, какие выводы из него можно сделать.
NPE может произойти в трёх случаях:
- Его кинули с помощью throw
- Кто-то кинул null с помощью throw
- Кто-то пытается обратиться по null-ссылке
Во втором и третьем случае message в объекте исключения всегда null, в первом может быть произвольным. К примеру, java.lang.System.setProperty кидает NPE с сообщением «key can’t be null», если вы передали в качестве key null. Если вы каждый входной параметр своих методов проверяете таким же образом и кидаете исключение с понятным сообщением, то вам остаток этой статьи не потребуется.
Обращение по null-ссылке может произойти в следующих случаях:
- Вызов нестатического метода класса
- Обращение (чтение или запись) к нестатическому полю
- Обращение (чтение или запись) к элементу массива
- Чтение length у массива
- Неявный вызов метода valueOf при анбоксинге (unboxing)
Важно понимать, что эти случаи должны произойти именно в той строчке, на которой заканчивается stack trace, а не где-либо ещё.
Рассмотрим такой код:
Откуда-то был вызван метод handle с какими-то параметрами, и вы получили:
В чём причина исключения — в f, d или d.val? Нетрудно заметить, что f в этой строке вообще не читается, так как метод format статический. Конечно, обращаться к статическому методу через экземпляр класса плохо, но такой код встречается (мог, например, появиться после рефакторинга). Так или иначе значение f не может быть причиной исключения. Если бы d был не null, а d.val — null, тогда бы исключение возникло уже внутри метода format (в девятой строчке). Аналогично проблема не могла быть внутри метода getValue, даже если бы он был сложнее. Раз исключение в пятнадцатой строчке, остаётся одна возможная причина: null в параметре d.
Вот другой пример:
Снова вызываем метод handle и получаем
Теперь метод format нестатический, и f вполне может быть источником ошибки. Зато s не может быть ни под каким соусом: в девятой строке уже было обращение к s. Если бы s было null, исключение бы случилось в девятой строке. Просмотр логики кода перед исключением довольно часто помогает отбросить некоторые варианты.
С логикой, конечно, надо быть внимательным. Предположим, условие в девятой строчке было бы написано так:
Теперь в самой строчке обращения к полям и методам s нету, а метод equals корректно обрабатывает null, возвращая false, поэтому в таком случае ошибку в двенадцатой строке мог вызвать как f, так и s. Анализируя вышестоящий код, уточняйте в документации или исходниках, как используемые методы и конструкции реагируют на null. Оператор конкатенации строк +, к примеру, никогда не вызывает NPE.
Вот такой код (здесь может играть роль версия Java, я использую Oracle JDK 1.7.0.45):
Вызываем метод dump, получаем такое исключение:
В параметре pw не может быть null, иначе нам не удалось бы войти в метод print. Возможно, null в obj? Легко проверить, что pw.print(null) выводит строку «null» без всяких исключений. Пойдём с конца. Исключение случилось здесь:
В строке 473 возможна только одна причина NPE: обращение к методу length строки s. Значит, s содержит null. Как так могло получиться? Поднимемся по стеку выше:
В метод write передаётся результат вызова метода String.valueOf. В каком случае он может вернуть null?
Единственный возможный вариант — obj не null, но obj.toString() вернул null. Значит, ошибку надо искать в переопределённом методе toString() нашего объекта MyObject. Заметьте, в stack trace MyObject вообще не фигурировал, но проблема именно там. Такой несложный анализ может сэкономить кучу времени на попытки воспроизвести ситуацию в отладчике.
Не стоит забывать и про коварный автобоксинг. Пусть у нас такой код:
И такое исключение:
На первый взгляд единственный вариант — это null в параметре obj. Но следует взглянуть на класс MyContainer:
Мы видим, что getCount() возвращает Integer, который автоматически превращается в int именно в третьей строке TestNPE.java, а значит, если getCount() вернул null, произойдёт именно такое исключение, которое мы видим. Обнаружив класс, подобный классу MyContainer, посмотрите в истории системы контроля версий, кто его автор, и насыпьте ему крошек под одеяло.
Помните, что если метод принимает параметр int, а вы передаёте Integer null, то анбоксинг случится до вызова метода, поэтому NPE будет указывать на строку с вызовом.
В заключение хочется пожелать пореже запускать отладчик: после некоторой тренировки анализ кода в голове нередко выполняется быстрее, чем воспроизведение трудноуловимой ситуации.
Источник