[英]The NullPointerException
can someone please tell me why in the following line the code throws a NullPointer. 有人可以告诉我为什么在下面的代码中抛出NullPointer吗?
public List<ApplicationInfo> getAppInfos(Context myContext) {
PackageManager pm = myContext.getPackageManager();
List<ApplicationInfo> appInfo = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Collections.sort(appInfo, new ApplicationInfo.DisplayNameComparator(pm)); //throws Nullpointer
return appInfo;
}
I try to call this method from a seperate Thread (not the UIThread). 我尝试从单独的线程(而不是UIThread)调用此方法。 But i passed the Context from my Activity... If i call this method from my Activity(without passing the context for sure) it works fine.
但是我通过Activity传递了Context ...如果我从Activity调用了此方法(不确定是否传递上下文),则可以正常工作。
I appreciate any help. 感谢您的帮助。
Update regarding Comment: 有关评论的更新:
Thank you for your respone. 谢谢您的回应。 That's a tricky Thing.
那是一件棘手的事情。 Because the Code runs fine on Emulator with API 17 but not on my real device.
因为该代码可以在具有API 17的模拟器上正常运行,但不能在我的真实设备上运行。 And i got a cool Alcatel phone which is, for me, really tricky to get it run for usb Debugging(i think not just for me, the Support is awful).
而且我有一个很酷的阿尔卡特手机,对我来说,要在USB调试下运行它确实很棘手(我认为不仅对我而言,支持非常糟糕)。 Under some circumstances i achieved to Crash the app on the Emulator as well.
在某些情况下,我还实现了在模拟器上使应用程序崩溃的功能。 I only remember a nullpointerexception, but maybe i mixed something.
我只记得一个nullpointerexception,但也许我混了些。 But what i can say is that when i comment the Collections.sort... out.
但是我可以说的是,当我评论Collections.sort ...时。 The app runs on the device as well.
该应用程序也在设备上运行。 I'm sorry for being so confusing right now.
很抱歉现在如此混乱。 The only Thing i can say is that this line crashes my app on my device, but not on my Emulator and only if i call this from an seperate Thread.
我只能说的是,此行使我的应用程序在我的设备上崩溃,但在我的模拟器上没有崩溃,并且仅当我从单独的线程调用此代码时才崩溃。
I instantiate Context like this: 我实例化上下文是这样的:
final Context myContext = MyActivity.this;
And in the Thread i just call the method like this: 在线程中,我只是调用如下方法:
List<ApplicationInfo> myList = getAppInfos(myContext);
PHONE and Emulator are running with same Android Version! PHONE和Emulator使用相同的Android版本运行!
You are getting the nullPointerException
because pm
in: 您正在获取
nullPointerException
因为pm
在:
PackageManager pm = myContext.getPackageManager();
is returning null
. 返回
null
。 Without seeing how you get your context, it's hard to say why sometimes it's null
and sometimes it's not. 如果不了解如何获取上下文,很难说为什么有时为
null
而有时不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.