0

I am making a quiz application that welcomes the user by taking their name in first activity, that is what I have done so far. Now I want to print the name of the user in the ResultActivity as well, how to append one name in two different classes in same project?

Intent intent = new Intent(name.this, Main.class);
intent.putExtra("name", et.getText().toString());
startActivity(intent);

This is throwing name in Main class, i want the name in Result activity as well.

Thanks

Constant
  • 780
  • 1
  • 5
  • 19
Zeeshan Sardar
  • 235
  • 3
  • 15

4 Answers4

2

The easiest way to do that is to store user's name as keys and values inside a Shared Preferences file.

SharedPreferences - the right way

SharedPreferences provides easy way to store persist simple values on device's storage. We use it often to store some user's or application's preferences and share it between many places - like multiple Activities. (In your case, you want to store user's name and share it between multiple Activities).

Basically there are two main operations one can perform when using SharedPreferences in Android. That is store data and load data. You should:

  • Create a new SharedPreferences object.
  • Then get an Editor instance from that object. The Editor object will help you manipulate the data that you’ve stored.
  • Use putString, putBoolean methods to store a pair key/value.
  • Use getBoolean, getString to get the values you want.

Simply, use this custom method to save user's name:

 private void savePreferences(String key, String value) {
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString(key, value);
        editor.commit();
    }

Example of use:

savePreferences("name", et.getText().toString());

Now you can retrieve user's name from preference in wherever activity you want. (Result,Main...)

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", null);

Hope I helped. Happy Coding :D

MCHAppy
  • 1,012
  • 9
  • 15
1

Why not taking advantage from SharedPreferences ? you can find more here : https://stackoverflow.com/a/21055784/754783

Community
  • 1
  • 1
Hosein Hamedi
  • 322
  • 4
  • 16
1

you can send another intent from Main class to ResultActivity

String name = getIntent().getStringExtra("name");// get the string from previous activity

//pass the intent to the ResultActivity
Intent intent = new Intent(Main.this, ResultActivity.class);
            intent.putExtra("name", name);
            startActivity(intent);

Another approach that you can do is to save the name in a SharedPreference. for reference, click http://www.tutorialspoint.com/android/android_shared_preferences.htm

Genevieve
  • 450
  • 3
  • 9
0

in your result activity: in onCreate you can get the name by using

String name = getIntent().getStringExtra("name", "A_Default_String");