在另一个 Activity 中使用在一个 Activity 中获取的数据 [英] Using data fetched in one Activity in another Activity

查看:29
本文介绍了在另一个 Activity 中使用在一个 Activity 中获取的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 Web 服务器获取某些数据,例如 Activity_1 中的 userName.然后我想在 Activity_2

I get certain data like say userName in Activity_1 from a web server. Then i want to use the same data in Activity_2

所以我制作了这个用户名 Public Static 并在 Activity_2

so i made this userName Public Static and used like this in Activity_2

Activity_1.userName

但是当我在 Activity_2press Home Button 并在 5 分钟后重新打开应用程序时,这个 Activity_1.userName 变成 Null 因为 Activity_1 数据被破坏.我得到 NullPointerException

But then when i am in Activity_2 and press Home Button and reopen the application 5 mins later, this Activity_1.userName become Null since that Activity_1 data is destroyed. and I get NullPointerException

如何以简单的方式解决这个问题.

How to solve this in a simple way.

我只是举了一个 userName 的例子,但实际上它是其他一些每天都在变化的数据,比如今日新闻"

I just gave an example of userName but actually its some other data which changes everyday, like say "news of the day"

许多人会建议删除 public static 并将该用户名发送为:

Many would suggest to remove public static and send that userName as:

Intent.putExtra("user_name", userName);

但这和我正在做的不一样.我的意思是即使这样我也会得到 NullPointerException 对吗??

But isn't this same as what i am doing. I mean even this way i will get NullPointerException right??

推荐答案

有两种方法可以做到这一点.

There would be two ways to do this.

  1. 始终确保 Activity1 是应用程序中的起始活动.我的意思是,如果用户关闭应用程序并重新启动它,应用程序应该从 Activity1 再次获取数据.然后只去Activity2.另请注意,您可以使用 AsyncTask 从 Activity2 本身中的网络获取数据.

将 Activity1 中的数据保存在 SharedPreferences 和在 Activity2 中始终使用 SharedPreferences 来读取值.

Save the data from the Activity1 in SharedPreferences and in Activity2 always use the SharedPreferences to read the values.

这篇关于在另一个 Activity 中使用在一个 Activity 中获取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆