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.
您可以将MainActivity上下文传递给Connection构造函数,然后在TestMessageListener中执行以下操作:
MainActivity mainClass = (MainActivity) mContext;
You do not have any instance of MainActivity.
Solution is :
MainActivity mainClass = new MainActivity();
You haven't intialized mainClass, that's why you are getting null pointer . You can either create new Main activity(but remember that your map is not static , so any modifications that you made might be lost depending where you made them) like
MainActivity mainClass = new MainActivity();
Or Create a constructor in Connection
class which accepts context
and the pass Main Activity to it and later use it inside your TestMessageListener
. Eg
private MainAcitivity mainClass;
public Connection(Context context) {
mainClass = (MainAcitivity) context;
}
public class TestMessageListener implements MessageListener {
MainActivity mainClass = new MainActivity();
}
You need an instance of mainClass in order to interact with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.