androidnullpointerexceptionlocationfragmentgetview

calling getViewById in a class outside a Fragment generates null pointer exception and the content of


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");
                }
            }
        }
    }
}

Solution

  • 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: