如何在Android studio中使用intent (Java)在多个页面之间传递数据?



我想从MainActivity传递数据到我的应用程序中的所有其他活动。我想让用户键入她的名字,然后在每个页面上,我希望她的名字也显示在那里。

到目前为止,我只设法让数据在另一个活动中显示。

这是反馈类中的代码,用户将在其中键入她的名字/userName等。

@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);

这是页面中显示数据的代码:

@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);
}

我希望变量userName也显示在我的其他页面。我怎么做呢?

你可以把这个属性作为Extra传递给每个活动-但可能更容易保存在sharedPreferences中:在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);
}

和每个想要读取该属性的活动:

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