読者です 読者をやめる 読者になる 読者になる

Android で getMap() が null になる

これでは GoogleMap が null になってしまう。

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_map);
  setupMap();
}
private void setupMap () {
  final FragmentManager m = getSupportFragmentManager();
  final SupportMapFragment f = (SupportMapFragment)m.findFragmentById(R.id.map_flagment);

  GoogleMap map = f.getMap ();
}

解決方法1
待つ

private void setupMap () {

  final Handler hand = new Handler();

  Thread t = new Thread(){

    @Override
    public void run () {

      while (true) {

        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          // do nothing
        }

        final FragmentManager m = getSupportFragmentManager();
        final SupportMapFragment f = (SupportMapFragment)m.findFragmentById(R.id.map_flagment);
        final GoogleMap map = f.getMap ();

        if (map == null) continue;

        hand.post(new Runnable() {
          public void run() {
            MyMapActivity.this.onCreateMap(map);
          }
        });
        break;
      }
    }
  };
  t.start();
}

解決方法2
フラグメントを拡張する

public class CustomMapFragment extends SupportMapFragment {

  public interface Listener {

    public void onCreateGoogleMap (GoogleMap map);

  }

  public void setListener (Listener listener) {
    _listener = listener;
  }

  @Override
  public void onActivityCreated(android.os.Bundle savedInstanceState) {
    super.onActivityCreated (savedInstanceState);

    _listener.onCreateGoogleMap (getMap());
  }

  private Listener _listener;
}