0

Я пытаюсь добавить строку поиска на андроид-карты. Карта добавляется как один из фрагментов проекта. Похоже, что ошибка введена this. Любая помощь приветствуется. Заранее спасибо.Добавить кнопку поиска к картам

public class Maps extends Fragment { 
    //Initial code 

    public void onSearch(View view) { 
     EditText location_tf = (EditText) getView().findViewById(R.id.TFaddress); 
     String location = location_tf.getText().toString(); 
     List <Address> addressList = null; 

     if (location != null || !location.equals("")) 
     Geocoder geocoder = new Geocoder(this); 

     try { 
      addressList = geocoder.getFromLocationName(location, 1); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    Address address = addressList.get(0); 
    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); 
    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
} 

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <LinearLayout android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
     <EditText android:layout_width="287dp" 
      android:layout_height="wrap_content" 
      android:id="@+id/TFaddress"/> 
     <Button style="?android:attr/buttonStyleSmall" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Search" 
      android:id="@+id/button" 
      android:layout_gravity="right" 
      android:onClick="onSearch" /> 
     <com.google.android.gms.maps.MapView 
      android:id="@+id/map" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"/> 
    </LinearLayout> 

Ошибка:

Error:(83, 46) error: incompatible types: MAPS cannot be converted to Context 
Note: Some input files use or override a deprecated API. 
Note: Recompile with -Xlint:deprecation for details. 
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output.  
Error:Execution failed for task ':app:compileDebugJava'. Compilation failed; see the compiler error output for details. 

ответ

0

Согласно the documentation, то Geocoder конструктор ожидает Context, а не Fragment, поэтому эту линию

Geocoder geocoder = new Geocoder(this); 

должен быть

Geocoder geocoder = new Geocoder(getActivity()); 

Кроме того, принять во внимание, что вы можете захотеть добавить скобки в вашем if заявлении:

if (location != null || !location.equals("")) 
    Geocoder geocoder = new Geocoder(this); 

    try { 
     addressList = geocoder.getFromLocationName(location, 1); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

Спасибо за помощь. Однако после исправления моего кода, когда я пытаюсь запустить его, TomCat: java.lang.IllegalStateException: Не удалось найти метод onSearch (View) в родительском или предком контексте для андроида: атрибут onClick, определенный в классе вида android.support. v7.widget.AppCompatButton с id 'button' – Chid

+0

Попробуйте сделать свой 'onSearch (View view)' public: 'public onSearch (View view)' – antonio

+0

Пробовал это. Не повезло. – Chid

Смежные вопросы