简体   繁体   中英

Pass variable value to class (NOT intent) from home activity

I need to update a variable (via setter, I think) in a class that is not the intent class of a button. I need to set c to a given value in Creator from the Home activity. The chosen activity will then use Item Creator .

Home Activity:

    int c;

    public void setC(int c) {
        this.c = c;
    }

    public void one(View view) {
        setC(1);
        Intent intent = new Intent(this, One.class);
        startActivity(intent);
    }

    public void two(View view) {
        setC(2);
        Intent intent = new Intent(this, Two.class);
        startActivity(intent);
    }

    public void three(View view) {
        setC(3);
        Intent intent = new Intent(this, Three.class);
        startActivity(intent);
    }

    public void four(View view) {
        setC(4);
        Intent intent = new Intent(this, Four.class);
        startActivity(intent);
    }

    public int getC() {
        return c;
    }

}

Class I am trying to pass c to:

public class Creator{
    HomeActivity home = new HomeScreenActivity();
    private int c = home.getC();

If I manually change c 's value...

int c = 3;

... the class I want to receive it gets it fine. The issue seems to be getting the buttons to setC().

Thank you for any advice!

  1. As far as your original question, I'd suggest using intents :

    What's the best way to share data between activities?

  2. cricket_007 is correct: use startActivity() , not "new HomeScreenActivity()":

    https://developer.android.com/training/basics/firstapp/starting-activity.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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