android - 尝试在 Activity 之间传递数据

标签 android

我正在尝试使用此主题在两个 Activity 之间传递数据:

How do I pass data between Activities in Android application?

这个答案:

在您当前的 Activity 中,创建一个新的 Intent:

 Intent i = new Intent(getApplicationContext(), NewActivity.class);

 i.putExtra("new_variable_name","value");

 startActivity(i);

然后在新的 Activity 中,检索这些值:

    Bundle extras = getIntent().getExtras();
  
 if (extras != null) {
     
 String value = extras.getString("new_variable_name");
   
}

我的问题是,我没有成功..我有一个游戏包含一个叫做硬币的值,但它是一个 sharedperferences, 这是共享首选项的代码:(oncreate)

prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    coins = prefs.getInt("key2", 0);

现在我如何获得我在 Shop(Shop.java) 上获得的硬币数量来用它们买东西?

最佳答案

只需在您发送的 Activity 中传递您的硬币值(value),使用:

i.putExtra("new_variable_name",coins);

请注意,第二个参数是来自 SharedPreferences 的 int coins 值。

要在接收 Activity 上读取您的硬币值(int 值),您必须将其作为 Integer 读取,而不是作为 String .

所以,使用:

private int coinsValue = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();

 if (extras != null) {

     coinsValue = getIntent().getIntExtra("new_variable_name", 0);

}

好了,coinsValue 变量有您的值。

编辑:要在您的接收类中的任何地方使用 coinsValue,请在开始时将其声明为一个字段。

关于android - 尝试在 Activity 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589173/

相关文章:

c# - 在 Xamarin.Android 中将数据从一个 Activity 传递到另一个 Activity

android - 是否可以对 Android 应用程序中的耳机音量增大/减小键使用react?

android - 带灰色方 block 的通知背景

Android Studio : cannot resolve some symbol and method

android - 连接 USB 电缆后自动启动我的 android 应用程序。

android - 在android中垂直和水平 ScrollView

java - Windows 和 Mac 上的 Android 库项目

java - 在 ObjC 中检索 String 的字节会返回与 Java 不同的结果

Android 应用程序和库依赖项发生冲突

c# - 如何使用 content-desc 单击按钮