简体   繁体   中英

How do I pass data between multiple pages using intent (Java) in Android studio?

I want to pass data from the MainActivity to all other activities in my App. I want to let the User type her name, and then on each following page, I want her name to show up there too.

So far I only manage to let the data show up in one more acitvity.

This is the code in the feedback class, where the user will type her name/userName etc.

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

    public void thanks_Click(View view) {
        EditText nmeText = findViewById(R.id.txtNme);
        String nme = nmeText.getText().toString();
        Intent newPage = new Intent(this, thanksActivity.class);
        newPage.putExtra("USERNAME", nme);
        startActivity(newPage);

And this is the code in the page where the data will be visible:

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


        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String userName = extras.getString( "USERNAME");

            TextView thanks = findViewById(R.id.idThanks);
            thanks.setText("Thanks for the Quiz idea " + userName);
        }

I want the variable userName to show in my other pages as well. How do I do that?

You can keep passing that attribute as Extra for every activity - but is probably easier to save in in sharedPreferences: So, in MainActivity:

public void thanks_Click(View view) {
  EditText nmeText = findViewById(R.id.txtNme);
  String nme = nmeText.getText().toString();
  SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
  editor.putString("USERNAME", nme);
  editor.apply();
  Intent newPage = new Intent(this, thanksActivity.class);
  startActivity(newPage);
}

and every activity that wants to read that attribute:

String name = PreferenceManager.getDefaultSharedPreferences(this).getString("USERNAME", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM