how to pass extra intent to two activities
Asked Answered
B

3

1

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it

Main

public class MainActivity extends Activity {
Button ok;
EditText name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name=(EditText)findViewById(R.id.editText);
    Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
    name.setTypeface(font_a);
    ok=(Button)findViewById(R.id.button);
       Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
    ok.setTypeface(font_b);

    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            String nameStr = name.getText().toString();

            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            intent.putExtra("NAMEDATA",nameStr);
            startActivity(intent);

        }
    });

}

and this is activity 2 receiving it

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    t = (TextView)findViewById(R.id.textView3);
    Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
    t.setTypeface(font_b);
    String n = this.getIntent().getStringExtra("NAMEDATA");
    t.setText(n);

so please how would i reuse this?

Baden answered 10/1, 2014 at 22:33 Comment(1)
Do you need that name for one session or when ever the user opens the app?Zaria
E
3

Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:

public static final String PREFS_NAME = "MyPrefsFile";

Then, to save:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();

to load:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");

Once saved, the prefs are accessible for every activity.

So in your case, save the name when ok button is pressed:

ok.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        String nameStr = name.getText().toString();

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("name", nameStr);
        editor.commit();

        Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
        startActivity(intent);

    }
});

Then read it:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    t = (TextView)findViewById(R.id.textView3);
    Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
    t.setTypeface(font_b);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    String n = settings.getString("name", "defaultName");
    t.setText(n);

You can do similarly in every activity you need it. See docs here.

Expansible answered 10/1, 2014 at 22:39 Comment(7)
If you declared it in MainActivity, in other activities call like that: MainActivity.PREFS_NAMEExpansible
sorry could you elaborate? @ExpansibleBaden
my fault forgot public static final String PREFS_NAME = "MyPrefsFile"; sorry this was amazing by the way thank you for taking the time @ExpansibleBaden
sorry i get defaultName appear in Activity2?Baden
i also have a warning about sharedpreferenceedit() without a commit() call?Baden
Sorry, forgot to include a call to commit, see updated answer.Expansible
yeah i finally worked it out half hour ago lol thank you very muchBaden
P
1

You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.

  • Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
  • Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
  • Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
  • Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Penniepenniless answered 10/1, 2014 at 22:58 Comment(0)
L
0

Create class extending from Application class. Implement setter and getter inside that class like,

  public class GlobalClass extends Application {

            //create setters and getters here

        public void setUserInfo(String userInfo) {

     }
        public void getUserInfo() {
          return userInfo;
     }

   }

then you can use this from any activity like,

           GlobalClass app = (GlobalClass ) getApplication();
           app.getUserInfo();
Limann answered 10/1, 2014 at 22:58 Comment(1)
Personally I don't like this as it encourages global variables. The Intents and SharedPreferences are much programmer friendly -- in the sense -- it avoid bad-practices that may end your code up with unmanageable spaghetti code. On top, this is not thread-safe either.Vineland

© 2022 - 2024 — McMap. All rights reserved.