如何将值存储到不同的 activity

How to store value into different activity

在我的 android 应用程序中,MainActivity 中有一个名称的 EditText,我想将用户的输入发送到 2 个不同的 activity。怎么做?

这是我在 MainActivity 中的示例代码:

EditText Name = (EditText) findViewById(R.id.editText1);
String sName = Name.getText().toString();
Intent i = new Intent(getApplicationContext(),firstActivity.class);
i.putExtra("sName", sName);
startActivity(i);

Intent intent = new Intent(getApplicationContext(),secondActivity.class);
intent.putExtra("sName", sName);

这是我在 firstActivity 中的示例代码:

Intent i = getIntent();
String name = getStringExtra("sName");

secondActivity 中的示例代码:

Intent intent = getIntent();
String name = getStringExtra("sName");

在 firstActivity 中获取输入,但在 secondActivity 中未输入。

如果您想为所有活动共享或发送值,请使用 SharedPreference

Activity:

SharedPreferences sharedPref = getApplicationContext().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", sName);
editor.commit();

第二Activity:

SharedPreferences sharedPref = getApplicationContext().getPreferences(Context.MODE_PRIVATE);
String email = sharedPref.getString(keyString, defaultValue);

如果您想将一个值访问到另一个 classes/Activity/Fragments。

放入一个 class 并从其他 classes 访问。

 public static String getsName(Context context) {
    SharedPreferences pref = null;
    pref = context.getSharedPreferences("APPNAME", Context.MODE_PRIVATE);
    return pref.getString("sName", "");
}

public static void setsName(Context context, String Data) {
    SharedPreferences pref;
    SharedPreferences.Editor lock_editor;

    pref = context.getSharedPreferences("APPNAME", Context.MODE_PRIVATE);
    lock_editor = pref.edit();
    lock_editor.putString("sName", Data);
    lock_editor.commit();
}