Search code examples
javaandroidgetsetgetter-setter

How to set a value into a variable from one class and get that variable's value from other class?


I want to set data into a variable of a class and want to get data of that variable in another class.

I have tested an example. But i am getting null value.

Example class Data:

public class Data {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

In the MainActivity class I do the set:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Data data = new Data();
        data.setText("HELLO");
        System.out.println("GET from Main class: " + data.getText());

        // Call the get class method
        Test test = new Test();
        test.execute();
    }

Test class:

public class Test {

    public void execute() {

        Data data = new Data();
        System.out.println(" GET from Test class: " + data.getText());

    }

}

Output:

I/System.out: GET from Main class: HELLO
I/System.out:  GET from Test class: null

How do I access to the Main class get?

Thanks.


Solution

  • You need to say that the data variable is a static variable, that means it's the same for all instances of Data. Once you've done that, you don't need an instance of Data.

    public class Data {
        private static String sText;
    
        public static String getText() {
            return sText;
        }
    
        public static void setText(String text) {
            sText = text;
        }
    }
    

    Then you call data statically. Data.getText() and Data.setText("hello")

    edit: But as Stultuske writes, you should brush up on the basics. My "solution" will fix your test but it's not a good one since making everything global will lead to a mess as soon as you start working on larger applications.