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

typ*_*er2 0 java android

Screen2.java文件具有以下代码:

public class screen2 extends Activity {

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

}
Run Code Online (Sandbox Code Playgroud)

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);

    }
Run Code Online (Sandbox Code Playgroud)

现在我遇到的问题是,如果我在Screen2.java文件中将globalZip的值更新为90034,则不会在screen3中更新.任何人都可以帮我解决这个错误.谢谢.

C0d*_*ack 5

好吧,你正在创建一个新的Screen2实例,所以你当然会返回globalZip的初始值,因为它不是一个静态类成员.

说,你可能不希望它成为一个静态成员.

但更重要的是,你真的错了.如果您想将数据从一个Activity传递到另一个Activity,您只需要将字符串/布尔值/整数等简单数据添加到启动Screen3的Intent中.

像这样的东西:

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

然后在Screen3.java中获取值:

Bundle extras = getIntent().getExtras();
int globalZip = extras.getInt("screen2.globalzip");
Run Code Online (Sandbox Code Playgroud)