Using data fetched in one Activity in another Activity

跟風遠走 提交于 2019-12-19 04:12:24

问题


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??


回答1:


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.




回答2:


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.




回答3:


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




回答4:


As swayam suggested, i will suggest you yo go for a DB or Shared prefs, Especially Shared prefs suits best for your scenario;

You can use something like as follows:

To Put:

SharedPreferences sharedPreferences = getSharedPreferences("PREFS_READ",
                Context.MODE_WORLD_READABLE);
        Editor prefsPrivateEditor = sharedPreferences.edit();
        prefsPrivateEditor.putString("yourkey", userName);
prefsPrivateEditor.commit();

To Get:

SharedPreferences sharedPreferences;
        Context otherAppsContext = null;
        try {
            otherAppsContext = getApplication().createPackageContext(
                    "your.package.name", 0);
        } catch (NameNotFoundException e) {
            Toast.makeText(Email.this, e.toString(), Toast.LENGTH_LONG).show();
        }
        sharedPreferences = otherAppsContext.getSharedPreferences("PREFS_READ",
                Context.MODE_WORLD_WRITEABLE);

        String getusername = sharedPreferences.getString("yourkey","default_value");


来源:https://stackoverflow.com/questions/12226761/using-data-fetched-in-one-activity-in-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!