2013-02-16 14 views
9

Nie mogę uzyskać mapy! wszystko, co mogę uzyskać, jest puste.w google maps V2 ... fragment.getMap() zwraca wartość null

tutaj jest kod.

 public class MainActivity extends FragmentActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     SupportMapFragment fragment = new SupportMapFragment(); 
     getSupportFragmentManager().beginTransaction() 
       .add(android.R.id.content, fragment).commit(); 


     GoogleMap map; 
     map = fragment.getMap(); 
      //here i cant access this snippet because map = null 
     if(map!=null){ 
     UiSettings mm = map.getUiSettings(); 
     map.setMyLocationEnabled(true); 
      } } 
      } 

Manifest:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.anywhere_reminder" 
android:versionCode="1" 
android:versionName="1.0" > 

    <uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="17" /> 
    <uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true"/> 

    <permission 
    android:name="com.example.anywhere_reminder.permission.MAPS_RECEIVE" 
    android:protectionLevel="signature" /> 

<uses-permission android:name="com.example.anywhere_reminder.permission.MAPS_RECEIVE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"  /> 

    <application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity android:name="com.google.android.gms.BuildConfig" /> 
    <activity 
     android:name="com.example.anywhere_reminder.MainActivity" 
     android:label="@string/app_name" > 

     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
     </activity> 

    <meta-data 
    android:name="com.google.android.maps.v2.API_KEY" 
    android:value=" my key "/> 

    </application> 
    </manifest> 

oto xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity" > 


<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/map" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
class="com.google.android.gms.maps.MapFragment"/> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" 
    android:text="@string/hello_world" /> 

    </RelativeLayout> 

Starałem się go rozwiązać jak to rozwiązanie Google Maps Android API v2 throws GooglePlayServicesNotAvailableException, out of date, SupportMapFragment.getMap() returns null .. ale nadal nie działa

AKTUALIZACJA:

Dostałem mapę pracuje teraz .. tutaj jest edytowany wersja działa

public class MainActivity extends FragmentActivity { 
private GoogleMap myMap; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

      android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager(); 
      SupportMapFragment mySupportMapFragment 
      = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map); 


      myMap = mySupportMapFragment.getMap(); 
      if(myMap!=null) 
      myMap.setMyLocationEnabled(true); 


     } 
+0

rozwiązanie aktualizacja dostał pracę dla mnie. +1 –

Odpowiedz

17

Tworzysz dynamiczny fragment, poprzez FragmentTransaction. Kiedy dzwonisz pod numer commit(), ten fragment został już dodany do ekranu , a nie, ponieważ FragmentTransaction został zaplanowany tylko do wykonania - jeszcze się nie pojawił. W związku z tym SupportMapFragment nie został jeszcze wywołany z onCreateView(), więc nie ma GoogleMap.

Można przejść do fragmentów statycznych (tag <fragment> w layoucie) lub opóźnić korzystanie z GoogleMap do czasu przetworzenia transakcji.

+0

Przepraszam: $, ale jak mogę opóźnić użycie GoogleMap, próbowałem wywołać je onResume() i nie działało. Nie wiem, czy to masz na myśli – proG

+0

@proG: Po wywołaniu 'commit()' na transakcja, wywołaj 'post()' na niektórych 'Widok' (lub' Handler' jeśli masz). Do czasu wywołania 'Runnable', które planujesz,' GoogleMap' powinno istnieć. Lub ponownie przełącz się na statyczne fragmenty. – CommonsWare

+0

@CommoneWare Przeczytam o nich .. dziękuję – proG

6

Wykonanie executePendingTransactions() w klasie FragmentManager zostało zaprojektowane w celu naprawienia tego opóźnienia. Od dokumantstion: Po tym jak FragmentTransaction zostanie zatwierdzony przez FragmentTransaction.commit(), zaplanowane jest jego wykonanie asynchroniczne w głównym wątku procesu. Jeśli chcesz natychmiast wykonać wszystkie takie operacje oczekujące, możesz wywołać tę funkcję (tylko z głównego wątku), aby to zrobić. Pamiętaj, że wszystkie wywołania zwrotne i inne podobne zachowania będą wykonywane z poziomu tego połączenia, więc należy uważać, skąd się to bierze.

+4

po wywołaniu 'fragMan.executePendingTransactions()' również nie mogę uzyskać mapy, ten sam ** wyjątek NullPointerEx ** wystąpił – Mani

+0

Próbowałem również 'executePendingTransactions' również i nadal jest puste po wywołaniu go. –

1

Innym sposobem rozwiązania problemu. Implemet interfejs w MapFragment, aby komunikował się z działaniem, gdy jest gotowy do utworzenia GoogleMap.

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onActivityCreated(savedInstanceState); 
    listener.onGoogleMapCreattion(); 


} 

Następnie wystarczy zaimplementować słuchacza w activtiy:

@Override 
public void onGoogleMapCreation() { 
    setUpMapIfNeeded(); 

} 

    private void setUpMapIfNeeded() { 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (mMap == null) { 
     mMap = mMapFragment.getMap(); 
     // Check if we were successful in obtaining the map. 
     if (mMap != null) { 
      // The Map is verified. It is now safe to manipulate the map. 
      setUpMap(); 

     } 
    } 
    } 
+0

Najlepsza odpowiedź. Poradzenie sobie z asynchroniczną naturą procesu tworzenia jest właściwą drogą do przejścia na IMO. Coś jeszcze, a twoje zwykłe zgadywanie, że już teraz jest właściwym momentem na uzyskanie dostępu do obiektu. –

3

Move fragment kodu:

GoogleMap map; map = fragment.getMap();

// tutaj mapa nie jest null

if (mapa! = Null) {

UiSettings mm = map.getUiSettings(); 
map.setMyLocationEnabled(true); 

}

do onResume() metoda, to rozwiąże problem.

6

Rozszerzyłem klasę MapFragment i dodano detektor. Dokument o getMap() mówi:

... Null, jeśli widok fragmentu nie jest jeszcze gotowy. Może się to zdarzyć, jeśli lifecyle fragment nie przeszły onCreateView (LayoutInflater, ViewGroup, Bundle) jeszcze ....

Potem zadzwoń do słuchacza po onCreateView. I dodać klasę

public class MySupportMapFragment extends SupportMapFragment{ 

private MySupportMapFragmentListener listener; 

public interface MySupportMapFragmentListener{ 
    public void onMapCreated(GoogleMap googleMap); 
} 

// value taken from source code 
private static final String MAP_OPTIONS = "MapOptions"; 

public static MySupportMapFragment newInstance() { 
     MySupportMapFragment f = new MySupportMapFragment(); 
     return f; 
} 

public static MySupportMapFragment newInstance(GoogleMapOptions options) { 
     MySupportMapFragment f = new MySupportMapFragment(); 
     Bundle args = new Bundle(); 
     args.putParcelable(MAP_OPTIONS, options); 
     f.setArguments(args); 
     return f; 
} 

// other newInstance methods ... 


/* (non-Javadoc) 
* @see android.support.v4.app.Fragment#onViewCreated(android.view.View, android.os.Bundle) 
*/ 
@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onViewCreated(view, savedInstanceState); 
    // here, as doc say, the map can be initialized, or the service is not available 
    if(listener!=null){ 
     listener.onMapCreated(getMap()); 
    } 

} 
/** 
* @return the listener 
*/ 
public MySupportMapFragmentListener getListener() { 
    return listener; 
} 
/** 
* @param listener the listener to set 
*/ 
public void setListener(MySupportMapFragmentListener listener) { 
    this.listener = listener; 
} 

}

Po aktywności wywołującej lub fragmentu ...

mapFragment = MySupportMapFragment.newInstance(); 
    mapFragment.setListener(new MySupportMapFragmentListener() { 
     @Override 
     public void onMapCreated(GoogleMap googleMap) { 
      // TODO Auto-generated method stub   
      if(googleMap!=null){ 
        // service is unaviable 
      }    
     } 
+0

bardzo dobre rozwiązanie, w tej chwili wydaje się być optymalnym – user2302510

+0

Nie możesz po prostu użyć bezpośrednio metody onViewCreated? – Tiago

Powiązane problemy