我一直在尝试在我的2 AutoCompleteTextView中添加位置的预测列表,我也在项目中实现了它,但是现在我的Dashboardactivity在设置适配器时出错。设置适配器时的错误类型转换错误类型
activity_dashboard.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/map_marker"
/>
<RelativeLayout
android:id="@+id/pickupRL"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_height="50dp"
android:layout_marginTop="5pt"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:elevation="4pt"
android:background="@drawable/white_border" >
<ImageView
android:id="@+id/pickupIV"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginRight="3pt"
android:layout_centerVertical="true"
android:layout_marginLeft="5pt"
android:src="@drawable/ic_search"
app:tint="@color/colorPrimaryDark"/>
<AutoCompleteTextView
android:id="@+id/pickupATV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/pickupIV"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="@color/colorBlack"
android:background="@null"
android:hint="Search location"
android:singleLine="true"
android:imeOptions="actionSearch"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/dropoffRL"
android:layout_marginTop="5pt"
android:layout_below="@id/pickupRL"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:elevation="4pt"
android:background="@drawable/white_border" >
<ImageView
android:id="@+id/dropoffIV"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginRight="3pt"
android:layout_centerVertical="true"
android:layout_marginLeft="5pt"
android:src="@drawable/ic_search"
app:tint="@color/colorPrimaryDark"/>
<AutoCompleteTextView
android:id="@+id/dropoffATV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/dropoffIV"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="@color/colorBlack"
android:background="@null"
android:hint="Search location"
android:singleLine="true"
android:imeOptions="actionSearch"/>
</RelativeLayout>
<Button
android:id="@+id/btnconfirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="30dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:padding="20dp"
android:text="Comfirm" />
<com.google.android.material.floatingactionbutton.FloatingactionButton
android:id="@+id/currentLocationFAB"
android:backgroundTint="@color/colorWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/btnconfirm"
android:layout_alignParentRight="true"
android:layout_marginBottom="5pt"
android:layout_marginRight="10pt"
android:elevation="4pt"
app:fabSize="mini"
app:borderWidth="0dp"
app:elevation="4pt"
app:backgroundTint="@color/colorWhite"
android:src="@drawable/ic_current_location"
android:tint="@color/colorPrimaryDark"/>
</RelativeLayout>
Dashboardactivity.java
public class Dashboardactivity extends AppCompatactivity implements OnmapReadyCallback,View.OnClicklistener,GoogleApiClient.OnConnectionFailedListener {
private activity activity;
private GoogleMap mMap;
private static final String Tag = "MAP_actIVITY";
private static final String FINE_LOCATION = Manifest.permission.accESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.accESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_zoom = 15f;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40,-168),new LatLng(71,136));
private Boolean mLocationPermissionsGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
private final ThreadLocal<PlaceAutocompleteAdapter> mplaceAutoCompeleteAdapter = new ThreadLocal<>();
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
private AutoCompleteTextView pickupATV,dropoffATV;
private Button btnconfirm;
private FloatingactionButton currentLocationFAB;
private Toolbar toolbar;
private MenuItem previousItem;
private UtilityModel utilityModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
bindControls();
bindListeners();
getLocationPermission();
setMap();
}
private void getLocationPermission() {
String[] permissions = {Manifest.permission.accESS_FINE_LOCATION,Manifest.permission.accESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getapplicationContext(),FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getapplicationContext(),COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
setMap();
} else {
activityCompat.requestPermissions(this,permissions,LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
activityCompat.requestPermissions(this,LOCATION_PERMISSION_REQUEST_CODE);
}
}
private void bindControls() {
activity = Dashboardactivity.this;
utilityModel = new UtilityModel(activity);
toolbar = findViewById(R.id.toolbar);
btnconfirm = findViewById(R.id.btnconfirm);
pickupATV = findViewById(R.id.pickupATV);
dropoffATV = findViewById(R.id.dropoffATV);
currentLocationFAB = findViewById(R.id.currentLocationFAB);
}
private void bindListeners() {
btnconfirm.setOnClicklistener(this);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(com.google.android.gms.location.places.Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this,this)
.build();
mplaceAutoCompeleteAdapter.set(new PlaceAutocompleteAdapter(activity,mGoogleApiClient,LAT_LNG_BOUNDS,null));
pickupATV.setOnItemClicklistener(mAutocompleteclicklistener);
pickupATV.setadapter(mplaceAutoCompeleteAdapter); // This adapter is causing the trouble
pickupATV.setOnEditoractionListener(new TextView.OnEditoractionListener() {
@Override
public boolean onEditoraction(TextView textView,int actionId,KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_actION_SEARCH
|| actionId == EditorInfo.IME_actION_DONE
|| keyEvent.getaction() == KeyEvent.actION_DOWN
|| keyEvent.getaction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geoLocate(pickupATV);
}
return false;
}
});
dropoffATV.setOnItemClicklistener(mAutocompleteclicklistener);
mplaceAutoCompeleteAdapter.set(new PlaceAutocompleteAdapter(activity,null));
dropoffATV.setadapter(mplaceAutoCompeleteAdapter); // This adapter is causing the trouble
dropoffATV.setOnEditoractionListener(new TextView.OnEditoractionListener() {
@Override
public boolean onEditoraction(TextView textView,KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_actION_SEARCH
|| actionId == EditorInfo.IME_actION_DONE
|| keyEvent.getaction() == KeyEvent.actION_DOWN
|| keyEvent.getaction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geoLocate(dropoffATV);
}
return false;
}
});
currentLocationFAB.setOnClicklistener(this);
utilityModel.hideSoftKeyboard();
}
private AdapterView.OnItemClicklistener mAutocompleteclicklistener = new AdapterView.OnItemClicklistener() {
@Override
public void onItemClick(AdapterView<?> adapterView,View view,int i,long l) {
utilityModel.hideSoftKeyboard();
final AutocompletePrediction item = mplaceAutoCompeleteAdapter.get().getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient,placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
@SuppressLint("RestrictedApi")
@Override
public void onResult(@NonNull PlaceBuffer places) {
if(!places.getStatus().isSuccess()){
Log.d(Tag,"onResult: Place query did not complete successfully: " + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(Tag,"onResult: name: " + place.getName());
mPlace.setaddress(place.getaddress().toString());
Log.d(Tag,"onResult: address: " + place.getaddress());
mPlace.setattributions(place.getattributions().toString());
// Log.d(TAG,"onResult: attributions: " + place.getattributions());
mPlace.setId(place.getId());
Log.d(Tag,"onResult: id:" + place.getId());
mPlace.setLatlng(place.getLatLng());
Log.d(Tag,"onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(Tag,"onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(Tag,"onResult: ic_phone number: " + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(Tag,"onResult: website uri: " + place.getWebsiteUri());
Log.d(Tag,"onResult: place: " + mPlace.toString());
}catch (NullPointerException e){
Log.e(Tag,"onResult: NullPointerException: " + e.getMessage() );
}
setMarkerAndmoveCamera(new LatLng(place.getViewport().getcenter().latitude,place.getViewport().getcenter().longitude),mPlace);
currentLocationFAB.setVisibility(View.VISIBLE);
places.release();
}
};
private void geoLocate(AutoCompleteTextView view) {
String searchString = view.getText().toString().trim();
Geocoder geocoder = new Geocoder(activity);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString,1);
} catch (IOException e) {
Log.e(Tag,"geoLocate: IOException: " + e.getMessage());
}
if (list.size() > 0) {
Address address = list.get(0);
setMarkerAndmoveCamera(new LatLng(address.getLatitude(),address.getLongitude()),null);
}
}
private void setMap() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onmapReady(GoogleMap googleMap) {
mMap = googleMap;
if (mLocationPermissionsGranted) {
getcurrentLocation();
if (activityCompat.checkSelfPermission(this,Manifest.permission.accESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && activityCompat.checkSelfPermission(this,Manifest.permission.accESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
@SuppressLint("RestrictedApi")
@Override
public void onCameraMove() {
currentLocationFAB.setVisibility(View.VISIBLE);
}
});
mMap.setOnmarkerDragListener(new GoogleMap.OnmarkerDragListener() {
@Override
public void onmarkerDragStart(Marker marker) {
}
@Override
public void onmarkerDrag(Marker marker) {
}
@SuppressLint("RestrictedApi")
@Override
public void onmarkerDragEnd(Marker marker) {
setMarkerAndmoveCamera(marker.getPosition(),null);
currentLocationFAB.setVisibility(View.VISIBLE);
}
});
mMap.setOnmapClicklistener(new GoogleMap.OnmapClicklistener() {
@SuppressLint("RestrictedApi")
@Override
public void onmapClick(LatLng latLng) {
setMarkerAndmoveCamera(latLng,null);
currentLocationFAB.setVisibility(View.VISIBLE);
}
});
}
}
private void getcurrentLocation() {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionsGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Log.d(Tag,"onComplete: found location!");
Location currentLocation = (Location) task.getResult();
setMarkerAndmoveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),null);
} else {
Log.d(Tag,"onFailed: current location is null");
Toast.makeText(activity,"unable to get current location",Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e(Tag,"getcurrentLocation: SecurityException: " + e.getMessage());
}
}
private void setMarkerAndmoveCamera(LatLng latLng,PlaceInfo placeInfo){
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngzoom(latLng,DEFAULT_zoom));
}
@SuppressLint("RestrictedApi")
@Override
public void onClick(View v) {
if (v == btnconfirm) {
// LatLng currentMarkerLocation = mMap.getcameraPosition().target;
} else if (v == currentLocationFAB) {
currentLocationFAB.setVisibility(View.INVISIBLE);
getcurrentLocation();
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
PlaceInfo.java
public class PlaceInfo {
private String name;
private String address;
private String phoneNumber;
private String id;
private Uri websiteUri;
private LatLng latlng;
private float rating;
private String attributions;
public PlaceInfo(String name,String address,String phoneNumber,String id,Uri websiteUri,LatLng latlng,float rating,String attributions) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.id = id;
this.websiteUri = websiteUri;
this.latlng = latlng;
this.rating = rating;
this.attributions = attributions;
}
public PlaceInfo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getaddress() {
return address;
}
public void setaddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Uri getWebsiteUri() {
return websiteUri;
}
public void setWebsiteUri(Uri websiteUri) {
this.websiteUri = websiteUri;
}
public LatLng getLatlng() {
return latlng;
}
public void setLatlng(LatLng latlng) {
this.latlng = latlng;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getattributions() {
return attributions;
}
public void setattributions(String attributions) {
this.attributions = attributions;
}
@Override
public String toString() {
return "PlaceInfo{" +
"name='" + name + '\'' +
",address='" + address + '\'' +
",phoneNumber='" + phoneNumber + '\'' +
",id='" + id + '\'' +
",websiteUri=" + websiteUri +
",latlng=" + latlng +
",rating=" + rating +
",attributions='" + attributions + '\'' +
'}';
}
}
PlaceAutocompleteAdapter.java
public class PlaceAutocompleteAdapter
extends ArrayAdapter<AutocompletePrediction> implements Filterable {
private static final String TAG = "PlaceAutocompleteAd";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
private ArrayList<AutocompletePrediction> mResultList;
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private AutocompleteFilter mPlaceFilter;
public PlaceAutocompleteAdapter(Context context,GoogleApiClient googleApiClient,LatLngBounds bounds,AutocompleteFilter filter) {
super(context,android.R.layout.simple_expandable_list_item_2,android.R.id.text1);
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
public void setbounds(LatLngBounds bounds) {
mBounds = bounds;
}
@Override
public int getcount() {
return mResultList.size();
}
@Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
@Override
public View getView(int position,View convertView,ViewGroup parent) {
View row = super.getView(position,convertView,parent);
AutocompletePrediction item = getItem(position);
TextView textView1 = row.findViewById(android.R.id.text1);
TextView textView2 = row.findViewById(android.R.id.text2);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
textView2.setText(item.getSecondaryText(STYLE_BOLD));
return row;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<AutocompletePrediction> filterData = new ArrayList<>();
if (constraint != null) {
filterData = getautocomplete(constraint);
}
results.values = filterData;
if (filterData != null) {
results.count = filterData.size();
} else {
results.count = 0;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint,FilterResults results) {
if (results != null && results.count > 0) {
mResultList = (ArrayList<AutocompletePrediction>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
@Override
public CharSequence convertResultToString(Object resultvalue) {
if (resultvalue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultvalue).getFullText(null);
} else {
return super.convertResultToString(resultvalue);
}
}
};
}
private ArrayList<AutocompletePrediction> getautocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i(TAG,"Starting autocomplete query for: " + constraint);
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getautocompletePredictions(mGoogleApiClient,constraint.toString(),mBounds,mPlaceFilter);
AutocompletePredictionBuffer autocompletePredictions = results
.await(60,TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getcontext(),"Error contacting API: " + status.toString(),Toast.LENGTH_SHORT).show();
Log.e(TAG,"Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i(TAG,"Query completed. Received " + autocompletePredictions.getcount()
+ " predictions.");
return DataBufferUtils.freezeAndClose(autocompletePredictions);
}
Log.e(TAG,"Google API client is not connected for autocomplete query.");
return null;
}
}
我的错误位于Dashboardactivity.java
和bindListener
上的pickupATV.setadapter
方法的dropoffATV.setadapter
中
构建错误
任务:app:compileDebugJavaWithJavac FAILED失败 /Users/muhammadyousuf/StudioProjects/homemoversfyp/app/src/main/java/com/example/daniyal/fyp_project/activities/Dashboardactivity.java:162: 错误:无法在类AutoCompleteTextView中使用方法setadapter 适用于给定的类型; pickATV.setadapter(mplaceAutoCompeleteAdapter); //此适配器引起麻烦 ^必需:T找到:ThreadLocal原因:推断类型不 符合上限 推断:ThreadLocal 上限:ListAdapter,Filterable,其中T是类型变量: T扩展了ListAdapter,在setadapter(T)方法中声明的Filterable /Users/muhammadyousuf/StudioProjects/homemoversfyp/app/src/main/java/com/example/daniyal/fyp_project/activities/Dashboardactivity.java:181: 错误:无法在类AutoCompleteTextView中使用方法setadapter 适用于给定的类型; dropoffATV.setadapter(mplaceAutoCompeleteAdapter); //此适配器引起麻烦 ^必需:T找到:ThreadLocal原因:推断类型不 符合上限 推断:ThreadLocal 上限:ListAdapter,Filterable,其中T是类型变量: T扩展方法setadapter(T)中声明的ListAdapter,Filterable注意:某些输入文件使用或覆盖不推荐使用的 API。注意:有关详细信息,请使用-Xlint:deprecation重新编译。注意: /Users/muhammadyousuf/StudioProjects/homemoversfyp/app/src/main/java/com/example/daniyal/fyp_project/activities/Dashboardactivity.java 使用未经检查或不安全的操作。注意:重新编译 -Xlint:未经检查以获取详细信息。 2个错误
失败:构建失败,并出现异常。
出了什么问题:任务执行失败 ':app:compileDebugJavaWithJavac'。编译失败;见编译器 错误输出以获取详细信息。