Search code examples
javaandroidnullencapsulation

Getters returning null


I know why my problem is occurring but i'm unsure on how to deal with it.

So I have 3 classes, 1 of these holds my getters & setters. In one class I am setting the values, in the other I am getting the values. When I get the values they are returned null. This is obviously because the two instances of the getter/setter object I created in the classes are separate from one another. What i'm trying to find out is how I can set the values in one class and get them in another without having two separate instances of the getter/setter class. My wording is terrible so here's a more visual explanation:

Class 1

Encapsulation encap = new Encapsulation();
encap.setValue(10);

Class 2

Encapsulation encap = new Encapsulation();
encap.getValue(); //I want this to return 10

Class 3 (Encapsulation)

private int value;

public void setValue(int value){
    this.value = value;
}

public int getValue(){
    return value
}

Solution

  • In Class2, you are creating a new instance of class Encapsulation. (Notice new Encapsulation()). So obviously, that won't hold the values.

    Instead, I would suggest you two solutions:

    First:

    Save that object in an Application class as you are working on Android application.

    public class TestApplication extends Application {
        public Encapsulation tempClass;
        public TestApplication () {
            // TODO Auto-generated constructor stub
        }
    
        @Override
        public void onCreate() { 
            // TODO Auto-generated method stub
            super.onCreate();
        }
    
        public Encapsulation getTempClass() {
            return tempClass;
        }
    
        public void setTempClass(Encapsulation tempClass) {
            this.tempClass  = tempClass;
        }
    }
    

    Now in your Activity:

    //after setContentView
    testAppObj = (TestApplication) getApplication();
    testAppObj.setTempClass(myTempClassObj);
    
    //retrieve as:
    Encapsulation obj = testAppObj.getTempClass();
    

    You must register your Application class in your manifest file just like you register your activities:

    <application
            android:name="com.pkg.test.TestApplication " />
    

    Second:

    Keep object encap as static in Class1. So you can access it from calss2. (I don't prefer static.)

    Hope it helps.