使用在一个活动的另一个活动读取的数据 [英] Using data fetched in one Activity in another Activity
问题描述
我得到这样说的userName
在 Activity_1
从Web服务器的特定数据。然后我想使用相同的数据在 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
所以我做了这个用户名公开
静态
并用这样的 Activity_2
so i made this userName Public
Static
and used like this in Activity_2
Activity_1.userName
但后来当我在 Activity_2
和 preSS主页按钮
键,5分钟后重新打开应用程序这个 Activity_1.userName
成为空
自认为 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.
我只是给了用户名的例子,但实际上它的其中每天都在变,像说的其他一些数据每日经济新闻
I just gave an example of userName but actually its some other data which changes everyday, like say "news of the day"
很多人会建议删除公开
静态
和发送该用户名的:
Many would suggest to remove public
static
and send that userName as:
Intent.putExtra("user_name", userName);
不过,这不就是一样的我在做什么。我的意思是,即使这样,我将获得 NullPointerException异常
右??
推荐答案
将会有两种方法可以做到这一点。
There would be two ways to do this.
-
务必确保活动1是在应用程序的启动活动。我的意思是,如果用户关闭应用程序,并再次重新启动它,应用程序应该从活动1,从而再次读取该数据。然后只去活性2。另外请注意,你可以做的获取从网络中活性2本身的数据通过的AsyncTask 。
从相关活动,将数据保存在共享preferences ,并在活性2始终使用共享preferences读值。
Save the data from the Activity1 in SharedPreferences and in Activity2 always use the SharedPreferences to read the values.
这篇关于使用在一个活动的另一个活动读取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!