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

本文是小编为大家收集整理的关于在另一个活动中使用一个活动中获取的数据的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

中使用相同的数据

所以我使这个用户名Public Static,在Activity_2

中使用它
Activity_1.userName

但是当我进入Activity_2和press Home Button时,并在稍后重新打开申请5分钟时,这个Activity_1.userName自该Activity_1 data is destroyed以来变为Null.我得到NullPointerException

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

我只是给了一个用户名的例子,但实际上它的一些其他数据每天更改,例如说"日报"

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

Intent.putExtra("user_name", userName);

但与我在做什么并非相同.我的意思是这种方式,我会得到NullPointerException右??

推荐答案

有两种方法可以这样做.

  1. 始终确保Activity1是应用程序中的起始活动.我的意思是,如果用户关闭应用程序并再次重新启动它,则应用程序应该来自Activity1并因此再次获取数据.然后只转到Activity2.另请注意,您可以通过使用 Asynctask来完成从Activity2本身中获取来自Activity2中的数据.

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

其他推荐答案

intent被保存,因此正确的答案是使用putextra.当您需要重新恢复活动时,将使用意图再次创建它.

其他推荐答案

您可以将一个操作添加到此事件,并仅在action存在的情况下捕获事件...

当然,您可以持久地保存数据 - SQLite数据库或SharedPreferences

本文地址:https://www.itbaoku.cn/post/102311.html

问题描述

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

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

Activity_1.userName

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);

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. Always make sure that Activity1 is the starting activity in your application. I mean, if the user closes the app and restarts it again, the application should from Activity1 and thus fetch the data again. And then only go to Activity2. Also note that you can do the fetching the data from the web in Activity2 itself by using AsyncTask.

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

其他推荐答案

The intent is saved so the correct answer is to use putExtra. When your activity needs to be reinstantiated, it will be created again using the intent.

其他推荐答案

you could add a action to this event and catch the event only if the action exists...

And of course you could save the data persistently - SQLite database or SharedPreferences