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

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

问题描述

我得到这样说的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是在应用程序的启动活动。我的意思是,如果用户关闭应用程序,并再次重新启动它,应用程序应该从活动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屋!

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