访问 API 和导航时的 Android 最佳实践
假设我有两个 Activity 要在 Android 中开发。当最终用户单击活动 A 中的按钮时,应用程序应该从 JSON API 中提取数据并将该信息呈现在活动 B 上。
所以我的问题是,最佳实践或模式是什么?即
- Activity A将调用AsyncTask并执行JSON调用。拉取数据,通过putExtra推送到Intent中,调用Activity B?
- Activity A 将调用 Activity B,Activity B onCreate 将调用 AsyncTask 并执行 JSON 调用?
- 其他建议?
哪一种是首选模式?
哪一个可以提供更好的用户体验? (例如,想象一下如果连接到服务器失败,错误对话框将在哪里。)
Let say that I have two Activity to develop in Android. Upon the end user click a button in Activity A, the application supposed to pull data off a JSON API and present that information on Activity B.
So my question is, what's the best practice or pattern? i.e.
- Activity A will call an AsyncTask and perform JSON call. Pull the data, push it into the Intent via putExtra, and call Activity B?
- Activity A will call Activity B, Activity B onCreate will call an AsyncTask and perform the JSON call?
- Other suggestions?
Which one is the prefer pattern?
And which gives better user experience? (e.g. imagine where the error dialog will be if connection fail to the server.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为通常情况下你的#2方法已经完成了。但在大多数情况下,您需要告诉 Activity B 从 JSON API 请求什么类型的信息。假设在活动 A 中您从列表中选择一个项目,活动 B 将获得有关该项目的更多信息。在此示例中,活动 A 将简单地传递对所选项目的引用,然后活动 B 可以使用该引用发出 JSON 请求以获取有关该项目的更多信息。这有道理吗?
我通常会尝试在 Intent extras 中传递尽可能少的信息,因此我会避开您的第一个解决方案。
I think normally something of your #2 approach is done. In most cases, though, you need to tell Activity B what type of information to request from the JSON API. So say in Activity A you are choosing an item from a list, and Activity B will get more information about that item. In this example Activity A will simply pass a reference to which item was selected, and then Activity B can use that reference to make a JSON request for more information about that item. Does that make sense?
I usually try to pass as little information as I can in Intent extras so I would steer clear of your first solution.