Use findViewById in Android Studio’s standard Mapsactivity

Asked

Viewed 34 times

0

I’m using the standard Maps template available on Android Studio, and in the activity_maps.xml added a EditText with the id towhere.

In the Mapsactivity class I just added a setOnFocusChangeListener:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        if(mapFragment != null)
            mapFragment.getMapAsync(this);

        /* início da parte feita por mim */
        EditText towhere =  findViewById(R.id.towhere); //ERRO
        towhere.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    Intent findAddress = new Intent(MapsActivity.this, FindAddress.class);
                    startActivity(findAddress);
                }
            }
        });
        /* fim da parte feita por mim */
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }
}

I get the error:

java.lang.Nullpointerexception: Attempt to invoke virtual method 'void android.widget.Edittext.setOnFocusChangeListener(android.view.View$Onfocuschangelistener)' on a null Object Reference

The setContentView is set before the findViewById, but it doesn’t work.

  • 1

    To help you will need more code (Mapsactivity and activity_maps.xml)

  • 1

    post plus part of code

  • I posted the whole class since I only added a few lines and it’s short.

1 answer

0

The problem was in XML. As I am running the Nexus emulator, it is getting the folder component layout-v26 instead of layout, and the archives activity_maps.xml of these two folders were different, and so was giving Nullpointerexception to the requested id on findViewById(R.id.towhere)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.