Using data fetched in one Activity in another Activity

前端 未结 4 1318
無奈伤痛
無奈伤痛 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: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");
    

提交回复
热议问题