简体   繁体   English

将变量从Java类传递给Android的另一个

[英]Passing a variable from Java class to another for Android

Screen2.java file has the following code : Screen2.java文件具有以下代码:

public class screen2 extends Activity {

    public int globalZip=0;
        //Some validations & update globalZip
        //Code control goes to Screen3,java

}

Screen3.java file has the following code : Screen3.java文件具有以下代码:

public class Screen3 extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen3);
        screen2 objs2= new screen2();
        int myzip = objs2.globalZip;

        Toast.makeText(getBaseContext(), "Screen3 "+myzip, 5).show();

        System.out.println("WTHDude"+"Screen3 "+myzip);

    }

Now the problem i am having that if i have updated value of globalZip in Screen2.java file as 90034 it is not getting updated in the screen3. 现在的问题是,如果我在Screen2.java文件中将globalZip的值更新为90034,则它在screen3中不会得到更新。 Can anyone help me with this error. 谁能帮我解决这个错误。 Thank you. 谢谢。

Well, you're creating a new instance of Screen2, so of course you will return the initial value of globalZip since it is not a static class member. 好的,您正在创建Screen2的新实例,因此您当然会返回globalZip的初始值,因为它不是静态类成员。

Saying that, you probably don't really want it to be a static member anyway. 话虽如此,您可能根本不希望它成为静态成员。

But more importantly you're going about this completely wrong. 但更重要的是,您要彻底解决这个问题。 If you want to pass data from one Activity to another Activity you just need to, for simple data like Strings/booleans/ints, add it to the Intent that starts Screen3. 如果要将数据从一个Activity传递到另一个Activity,只需将诸如Strings / booleans / ints之类的简单数据添加到启动Screen3的Intent中。

Something like this: 像这样:

// inside Screen2.java
Intent intent = new Intent(this, Screen3.class);
intent.putExtra("screen2.globalzip", globalZip);

And then to get the value in Screen3.java: 然后在Screen3.java中获取值:

Bundle extras = getIntent().getExtras();
int globalZip = extras.getInt("screen2.globalzip");

Use intents for passing data between activities. 使用意图在活动之间传递数据。 Here is and example. 这是示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM