2
AutoCompleteTextView autoCompView = 
          (AutoCompleteTextView) findViewById(R.id.autocomplete_city);

Gives me an error

The method findViewById is undefined for the type CityFragment.

with:

public class CityFragment extends Fragment {

    public CityFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.city,
                    container, false);

    AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) findViewById(R.id.autocomplete_city);

        autoCompView.setAdapter(
                       new PlacesAutoCompleteAdapter(this, R.layout.list_item)
                );

    return rootView;
    }
}

I basically just copied the code from https://developers.google.com/places/training/autocomplete-android

Any ideas why I get the error?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

4 Answers4

4

That is because indeed Fragment does not have such method findViewById(). Instead, you should use the rootView to access it.

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView)rootView.findViewById(R.id.autocomplete_city);
Andy Res
  • 15,963
  • 5
  • 60
  • 96
2

Change with :

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
2

Change:

AutoCompleteTextView autoCompView = 
          (AutoCompleteTextView) findViewById(R.id.autocomplete_city);

to:

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
1

Here rootView is the parent for AutoCompleteTextView. So change it with:

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
Swetank
  • 1,577
  • 11
  • 14