Using data fetched in one Activity in another Activity

前端 未结 4 1316
無奈伤痛
無奈伤痛 2021-01-06 23:54

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

相关标签:
4条回答
  • 2021-01-07 00:34

    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.

    0 讨论(0)
  • 2021-01-07 00:34

    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

    0 讨论(0)
  • 2021-01-07 00:38

    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");
    
    0 讨论(0)
  • 2021-01-07 00:55

    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.

    0 讨论(0)
提交回复
热议问题