2017-07-24 5 views
-1

Ich versuche, Gerät Geolocation in Fragment zu übertragen und Callback zu verwenden. Aber nach dem Satz einer Zeit Link ist nullWie setze ich CallBack in Kotlin?

fun updateLocation(location:LatLng){ 
    Log.d(TAG,"Update fragment "+ localUpdater+" "+location) 
    localUpdater?.tryOutLocation(location) 

} 
private inner class Receiver: BroadcastReceiver(){ 
    override fun onReceive(context: Context?, intent: Intent?) { 
     val bundle = intent?.extras!![AppConstants.LOCATION_BUNDLE] as Bundle 
     val location = bundle.get(AppConstants.LOCATION_BUNDLE) as LatLng 
     updateLocation(location)     
    } 
} 

fun setUpdater(updater: IUpdateLocation){ 
    this.localUpdater = updater 
    Log.d(TAG,"Update fragment1 "+localUpdater) 
} 

Ich erkläre Rückruf:

private var localUpdater: IUpdateLocation? = null 

-Code-Schnittstelle:

interface IUpdateLocation { 
    fun tryOutLocation(location:LatLng) 
} 

Fragment Code:

override fun onActivityCreated(savedInstanceState: Bundle?) { 
    act?.setUpdater(this) 
    super.onActivityCreated(savedInstanceState) 
} 


override fun tryOutLocation(location: LatLng) { 
    Log.d(TAG,"Update fragment map fragment "+location+" ") 
    if(gMap != null){ 
     gMap?.uiSettings?.isZoomGesturesEnabled 
     gMap?.addMarker(MarkerOptions().position(location).title("Test")) 
     gMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 20.0f)) 
} 

Zum ersten Mal callback is set and work (log)

aber nach dem ersten Aufruf Link ist null. Warum? Wie kann ich dieses Problem beheben?

+0

Nun, wenn es das erste Mal funktioniert, bedeutet dies, dass es die Methode onReceive nicht zum zweiten Mal aufruft und die updateLocation-Methode nicht aufruft. Das bedeutet, dass Sie eine Sendung nicht richtig senden. Ich nehme an, dass Sie es nicht in die onResume-Methode geschrieben haben, da onCreate nur einmal aufgerufen wird, weshalb es nur beim ersten Mal funktioniert. Ich rate nur hier :) – Nenco

+0

Was ist 'act'? Haben Sie sichergestellt, dass "act" in "onActivityCreated" nicht null ist? – Naetmul

+0

über welche "link" sprichst du? – chandil03

Antwort

0

Ich fand wo war der Fehler. Ich verwende übergeordnete BaseActivity, wo die innere Klasse Receiver ist. In SplashActivity, das von BaseActivity geerbt wurde, habe ich das Objekt Receiver erstellt und den Callback, den ich aus dem Fragment in MainActivity erstellt habe, auch geerbt von BaseActivity. Ich hatte eine Situation, als ich zuerst Callback einstellte und danach Reciever erstellte. Ich habe alle Prozesse in MainActivity ertragen und es funktioniert.