Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a variable from another class in java

Tags:

java

android

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 ?

like image 546
Okan Avatar asked Apr 23 '26 18:04

Okan


2 Answers

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.

like image 85
Pshemo Avatar answered Apr 26 '26 08:04

Pshemo


You could pass the MainActivity context to the Connection constructor and then in the TestMessageListener just do something like:

MainActivity mainClass = (MainActivity) mContext;
like image 42
MarcSB Avatar answered Apr 26 '26 07:04

MarcSB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!