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 I can't access conversationsMap from another class ?
MainActivity mainClass; is a field of nested class TestMessageListener so if you will not initialize it it will be initialized with default value which for references is null which means that
mainClass.conversationsMap.get("test");
will try to invoke conversationsMap.get("test") on null, but since null doesn't have any fields or methods you are getting NullPointerException.
Generally to solve this kind of problem you either initialize mainClass yourself with new instance
MainActivity mainClass = new MainActivity();
but probably better option is to let user or other process pass already created instance to TestMessageListener class. To do this you can create setter,
public void setMainActivity(MainActivity mainClass){
this.mainClass = mainClass;
}
or accept MainActivity in TestMessageListener constructor
public TestMessageListener(MainActivity mainClass){
this.mainClass = mainClass;
}
I am not Android developer so they can be even better ways, like maybe getting this instance from some kind registered Activity containers but I can't help you in this case.
You could pass the MainActivity context to the Connection constructor and then in the TestMessageListener just do something like:
MainActivity mainClass = (MainActivity) mContext;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With