I'm trying to change the text from a TextView
that is in a Fragment
when onLocationChanged
function is called.
I know that i could implement LocationListener
when creating HomeFragment
but i want this to be modularized.
public void onLocationChanged(Location location) {
Log.i(TAG,"onLocationChanged method called");
HomeFragment hf = new HomeFragment();
if(hf == null)
{
Log.i(TAG,"hf is null");
}
else {
if(hf.getView().findViewById(R.id.speed_box) == null)
{
Log.i(TAG,"findViewById failed");
}
else {
TextView speedBox = (TextView) hf.getView().findViewById(R.id.speed_box);
if (location == null) {
if (speedBox != null) {
speedBox.setText("unknown m/s");
} else {
Log.i(TAG, "speedBox object is null");
}
} else {
Log.i(TAG, "onLocationChanged method called, the speed is: " + location.getSpeed());
float speed = location.getSpeed();
if (speedBox != null) {
speedBox.setText(location.getSpeed() + " m/s");
}
{
Log.i(TAG, "speedBox object is null");
}
}
}
}
}
You create an instance of HomeFragment
, but it's not attached to the layout yet, that's why you get null
from getView
.
The fragment needs to be attached to Activity by a transaction from FragmentManager
, then fragment.onCreateView
is called, then getView
will not return null.
To me, the reason you don't want to use listener is not what it should be. Location callback should be global in a location-aware app, and any component needs to listen to location changed can register a listener anywhere.
Here is how I will implement it:
AppLocationManager
class that holds location logic, it keep the list of LocationListener and fire event to all listener if location changed. AppLocationManager
doesn't need to know about its dependencies or what they are, it only does 1 job.HomeFragment
registers the listener to AppLocationManager
in onCreateView
, listen to the change and update its TextView.AppLocationManager
if they want just like HomeFragment
.