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?

+3


source to share


5 answers


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.

+3


source


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



MainActivity mainClass = (MainActivity) mContext;

      

+2


source


You don't have an instance of MainActivity.

Decision:

MainActivity mainclass = new MainActivity ();

+1


source


public class TestMessageListener implements MessageListener {
           MainActivity mainClass = new MainActivity();
     }

      

You need an instance of mainClass to interact with it.

+1


source


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;
}

      

+1


source







All Articles