试图通过活动之​​间的数据 [英] Trying to pass data between activities

查看:157
本文介绍了试图通过活动之​​间的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着通过使用这一主题的两项活动之间的数据:

Im trying to pass data between two activities using this subject:

<一个href=\"http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android\">How我传递活动之间的数据,Android的?

在你当前活动,创建一个新的目标:

In your current Activity, create a new Intent:

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

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

 startActivity(i);

然后在新的活动,检索这些值:

Then in the new Activity, retrieve those values:

    Bundle extras = getIntent().getExtras();

 if (extras != null) {

 String value = extras.getString("new_variable_name");

}

我的问题是,我没有成功。我有一个游戏包含了一个叫做价值的硬币,但它是作为一个sharedperferences,
这里是共享preferences的code:(OnCreate中)

My problem is , I'm not success.. I have a game contains a value called coins but it is as a sharedperferences , here is the code of the sharedpreferences: (oncreate)

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

现在我如何才能买东西与他们我的店(Shop.java)得到了硬币的数量?

Now how do I get the amount of coins I got on the Shop(Shop.java) to buy things with them?

推荐答案

只是通过在发送活动的硬币值,,使用:

Just pass your coins value, in your sending Activity, using:

i.putExtra("new_variable_name",coins);

请注意,第二个参数是您的INT硬币价值共享preferences

Note that the second parameter is your int coins value from SharedPreferences.

要在接收读取你的硬币值(int值)活动你必须阅读它作为一个整数 ,而不是作为一个字符串

To read your coins value (int value) on the receiving Activity you have to read it as an Integer, not as a 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 变量都有自己的价值。

And there you go, coinsValue variable has your value.

编辑:要使用coinsValue在接收类的任意位置,声明它作为一个字段,开头。

To use coinsValue anywhere in your receiving class, declare it as a field, at the beginning.

这篇关于试图通过活动之​​间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆