简体   繁体   English

onActivityResult Android

[英]onActivityResult Android

I am new to android and have the following query. 我是android的新手,并有以下查询。

I am building an app, which contains 2 activities first and second which send messages to each other. 我正在构建一个应用程序,它包含第一个和第二个活动,它们相互发送消息。 'first' sends a message to 'second' and then 'second' starts, displays the message received and sends back a message to 'first'. 'first'向'second'发送消息然后'second'开始,显示收到的消息并将消息发送回'first'。 Finally first displays the message received. 最后,首先显示收到的消息。

In the first activity i have to start the second activity using startActivityForResult since i need a response back. 在第一个活动中,我必须使用startActivityForResult启动第二个活动,因为我需要回复。

Question - when overriding onActivityResult why do we have to check if(resultCode == RESULT_OK) 问题 - 当覆盖onActivityResult时,我们为什么要检查是否(resultCode == RESULT_OK)

According to the android website - 根据android网站 -

onActivityResult is "Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. " onActivityResult是“当您启动的活动退出时调用,为您提供启动它的requestCode,返回的resultCode以及来自它的任何其他数据。”

So if i have the set the ResultCode to Result_OK in 'second activity', why do i have to check resultCode in 'first' activity. 因此,如果我在“第二个活动”中将ResultCode设置为Result_OK,为什么我必须在'first'活动中检查resultCode。 ? Isnt onActivityResult called when the 'second' sets the resultCode and exits ? 当'second'设置resultCode并退出时,是否调用onActivityResult?

Thanks ! 谢谢 !

PS - i have tried removing the statement - if(resultCode == RESULT_OK) . PS - 我试过删除语句 - if(resultCode == RESULT_OK)。 I get a NullPointerException. 我得到一个NullPointerException。

Your activity may exits in two ways, first which sounds "normal" which you entered your message and maybe press some "done" button to finish it. 您的活动可能会以两种方式退出,首先是您输入消息时听起来“正常”,并且可能会按下一些“完成”按钮来完成它。 This way you're setting the result to OK. 这样您就可以将结果设置为OK。

There's second way which user may press on back button, so your activity ends without capturing user input, thus your onActivityResult may get nothing. 用户可以按下后退按钮的第二种方式,因此您的活动结束而不捕获用户输入,因此您的onActivityResult可能什么也得不到。 This way you get your null pointer exception, where you know user exited the activity 2 without entering proper input. 这样,您就会获得空指针异常,您知道用户在没有输入正确输入的情况下退出了活动2。

Hope you see why ResultCode is important in this case. 希望您了解为什么ResultCode在这种情况下很重要。

when you are in the second activity and you press the back key the second activity will be finished and the result code will not be 'OK'. 当您处于第二个活动并按后退键时,第二个活动将完成,结果代码将不会是“确定”。 So ResultCode is needed. 所以需要ResultCode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM