Ahmed
Ahmed

Reputation: 93

using variable in another class

Iam creating an android app that has many classes inside the main Java package. The MainActivity class implements Button onClick Listener and do some coding with assigning values to variable x inside the method when button is clicked, now I have class#2 use the same variable x in some other coding. I want the onClick method when it is called to send the variable x value to class#2

MainActivityCalss {

    hi.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            int x = 1;
        }
    });

}

Class2 {

    Method() {
        y = x + 1;
    }

}

Upvotes: 0

Views: 98

Answers (2)

Prashant Sable
Prashant Sable

Reputation: 1013

Creating a new Java class to hold all global variables is a very good idea.

public class GlovalVariable{
    public String x;
    public int y;
    // Generate getter/setter methods for all the variables defined here.
}

By creating this you will manage a variables very easily. If you want to rename the variable which is used through out the class, this method will make it very easy.

Upvotes: 1

WritingForAnroid
WritingForAnroid

Reputation: 711

Define "x" in other class and set it using setter method, and where ever you get it through getter.

public class value {
    public static int x;

    public static void set(int value) {
        x = value;
    }

    public static int get() {
        return x;
    }
}

And in onclicklistener of mainactivity.

hi.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        value.set(1);
    }
});

In class2

 Method() {
        y = value.get()+1;
    }

Upvotes: 0

Related Questions