0

I am trying to develop an android app with a google map v2, location service and some control buttons.

I don't want to put all these thing inside one MainActivity class so I thought I could split all the code into some more classes. The MainActivity shall controll all the GUI things and react on map or location events.

Now I have the following problem. Inside my onCreate I instanziate the additional classes:

// Preferences as singleton
pref = Prefs.getInstance(this.getApplicationContext());
pref.loadSettings();

// Set up the location
loc  = new Locations(pref);
loc.setCallback(this);

map = new MyMap(pref);

It seems to work fine. But inside the MyMap class every time I start the app a null pointer exception is thrown. I don't know why and how to prevent it. When calling MyMap() the following code will be executed:

[...]
private Prefs pref;
private GoogleMap mMap;
[...]

public MyMap(Prefs prefs) {
    pref = (Prefs) prefs;
    if (mMap == null) {
      FragmentManager fmanager = getSupportFragmentManager(); 
      mMap = ((SupportMapFragment) fmanager.findFragmentById(R.id.map)).getMap();
[...]
}

The line with the findFragmentById is the one that causes the exception. I think it is caused because the fragment manager cannot access the layout loaded inside my MainActivity. But how can I access the fragments and view elements defined within my MainActivity?

Every class has the following head:

public class XYZ extends android.support.v4.app.FragmentActivity implements XXX, YYY

I tried to save the application context within my Prefs() class. But I don't know how to use it inside my additional classes. :(

Can someone help me please?

Thank you very much!!!

Thorsten

  • Post your logcat. What line is throwing the null pointer? – Kaediil Feb 28 '13 at 20:07
  • [`NullPointerException`](http://developer.android.com/reference/java/lang/NullPointerException.html) –  Feb 28 '13 at 20:14
  • I broke down the problem to the findFragmentById(). If I write `SupportMapFragment f = ((SupportMapFragment) fmanager.findFragmentById(R.id.map)); ` f is allways null. It seems that findFragmentById does not find the fragment. It works if I put this code inside my MainActivity. – Ikarisan Feb 28 '13 at 20:47

1 Answers1

0

Try passing mainActivity.getContext() (not getApplicationContext()) as argument in your constructor method for MyMap and inside the constructor set that value to a type attribute . Then use that context for example: context.findViewById(...) or context.getText(...)

Good luck!

Nahuel Barrios
  • 1,870
  • 19
  • 22
  • Thank you! I am using this for now: ` public MyMap(Prefs prefs, SupportMapFragment mapFragment) { pref = prefs; mapFrag = mapFragment; } ` – Ikarisan Mar 07 '13 at 22:42