我正在尝试使用此主题在两个 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/