Accessing a variable from another class in java
I have a class like this:
MainActivity.java
public class MainActivity extends FragmentActivity {
/* I removed other methods */
public Map<String, Conversation> conversationsMap = new LinkedHashMap<>();
}
And Connection.java
public class Connection {
/* I removed other methods */
public class TestMessageListener implements MessageListener {
MainActivity mainClass;
public void someMethod() {
mainClass.conversationsMap.get("test"); /// This line is returning nullpointer exception
}
}
}
Why can't I access conversationsMap
from another class?
source to share
MainActivity mainClass;
is a nested class field TestMessageListener
, so if you don't initialize it, it will be initialized with a default value, which for references null
means
mainClass.conversationsMap.get("test");
will try to call conversationsMap.get("test")
on null, but since null
it has no fields or methods, you get a NullPointerException.
Typically, to solve this problem, you either initialize mainClass
yourself with a new instance
MainActivity mainClass = new MainActivity();
but probably the best option is to let the user or another process pass the already created instance to the class TestMessageListener
. For this, you can create a setter,
public void setMainActivity(MainActivity mainClass){
this.mainClass = mainClass;
}
or accept MainActivity
in constructorTestMessageListener
public TestMessageListener(MainActivity mainClass){
this.mainClass = mainClass;
}
I'm not an Android developer, so they could be even better, like maybe getting this instance from some registered containers Activity
, but I can't help you in that case.
source to share
You don't have an intialized mainClass, so you end up with a null pointer. You can either create a new Main Action (but remember that your map is not static, so any changes you make may be lost depending on where you created them), for example
MainActivity mainClass = new MainActivity();
Or create a constructor in the class Connection
that accepts context
and passes the main activity to it and then use it inside yours TestMessageListener
. For example.
private MainAcitivity mainClass;
public Connection(Context context) {
mainClass = (MainAcitivity) context;
}
source to share