문제

I have seen this and similar posts.

To me it seems that I do everything correctly.

Still,

SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);`

returns NULL.

activty_map.xml

<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >


<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>

<Button 
android:id="@+id/startgeo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Geo"
android:background="@android:color/transparent"
android:layout_gravity="right"/>

</FrameLayout>

Code in my Activity:

    setContentView(R.layout.activty_map);
    SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map); //RETURNS NULL !!!
    map = mapFrag.getMap();
도움이 되었습니까?

해결책

As per mentioned by some other devs, google maps take some while to load. That is why you need to call your map initialization code after some delay (lets say 500ms).

For example:

setContentView(R.layout.activty_map);

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map); //should'nt be null after 500ms
        map = mapFrag.getMap();
    }
}, 500);

Moreover, I would suggest you to rely on onResume method for confirm completion of loading.

다른 팁

Rather than just posting it using some arbitrary delay you can be sure the fragment will be available in in onResumeFragments, #http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onResumeFragments()

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top