Difference between getExtras(name).getString and getIntent().getStringExtra(name)

て烟熏妆下的殇ゞ 提交于 2019-12-22 05:01:20

问题


I have some error reports on my Android app, it's a Nullpointerexception in onCreate() in an Activity. The code that fails is getIntent().getExtras().getStringExtra("name"). (Nullpointerexception)

That means that getExtras() is null somehow. I am sure that I am setting the intent extra on every place I am creating the intent. I can't recreate it on my emulator on device. I think it happened on my real device (but not while I was debugging) after I tried to open the app again, in the mean time Android probably killed the process and recreated the activity again. But shouldn't be the intent extras kept even in this scenario?

I tried to kill the process on the emulator, onCreate was called again and the getExtras() returned the right value.

I replaced the code with getIntent().getStringExtra(). What's the difference besides it won't throw a nullpointerexception but will still set the String as null. Is there any other difference?

What could be causing it?


回答1:


Intent.getStringExtra() returns null if there are no extras. Intent.getExtras() returns null if there are no extras, so you need to check for that before trying to call getString() or other methods on it.




回答2:


getIntent.getExtras() is returning null at some point. getIntent().getStringExtra() is most likely coded to check for a null extras and to return null if getExtras() is null. So called "no throws" architecture. If so, this is valid runtime execution and would not throw an exception. calling getStringExtra on a null extras is not valid runtime execution and should throw an exception.

It appears that there IS a path where getExtras() is null, so you could code around this by checking for a null extras.




回答3:


I found out that somewhere else in my code I was creating shortcut intents which had a String[] extra. Android HOME (and maybe other parts of the system) don't persit string arrays, only primitive extras (int, string, long, float...). But the code that was causing problems doesn't use shortcuts, it's only a simple activity which receives a string array extra. Maybe the empty extras were caused by this problem too - the application was killed by OS and the extras could not be stored. No exception is thrown by Android in this case.

Described by Romain Guy here: http://groups.google.com/group/android-developers/browse_thread/thread/7f2ce458bd5d112f/189e2b7b2b2532d7

I asked a more specific question about this here: Shortcut intent extras lost after restart?



来源:https://stackoverflow.com/questions/5851649/difference-between-getextrasname-getstring-and-getintent-getstringextraname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!