Я пытаюсь создать текстовое представление с автозаполнением, и используется адаптер Google API. Когда я набираю текстовое представление автозаполнения, результатом должны были быть предложенные места из того, что я набрал, но я не получаю никаких предложений вообще. Пожалуйста, помогите мне, поскольку я новичок ie. Я пытался найти, не может найти какие-либо вопросы, основанные на этом. Любая помощь приветствуется. Я тестирую на своем телефоне Oneplus 7T, который работает на android 10. И у меня также есть стабильное соединение inte rnet.
Ожидаемый результат должен иметь места, предлагаемые как это
Но в моем случае вообще ничего не происходит.
PS Follow - https://github.com/AhsanMunir/Google-Places-SDK-for-Android
activity_main. xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:fillViewport="true">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:id="@+id/main_first">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="@string/trip_planner"
android:textSize="27sp"
android:textStyle="bold"
android:layout_margin="7dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="@string/let_s_get_your_trip_started"
android:textSize="18sp"
android:layout_margin="7dp"/>
<!--
<fragment android:id="@+id/start_off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_margin="7dp"/>
<fragment android:id="@+id/destination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_margin="7dp"/>
-->
<AutoCompleteTextView
android:id="@+id/auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:hint="Enter Starting Point" />
<!-- <AutoCompleteTextView
android:id="@+id/auto_dest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:hint="Enter Destination" /> -->
</LinearLayout>
</ScrollView>
<Button
android:id="@+id/plan_trip_btn"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="@string/let_s_plan_your_trip"
android:textSize="17sp"
/>
</RelativeLayout>
Mainactivity. java
public class MainActivity extends AppCompatActivity {
View view;
AutoCompleteTextView autoCompleteTextView,autodest;
AutoCompleteAdapter adapter,adapter_dest;
PlacesClient placesClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=findViewById(android.R.id.content).getRootView();
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.LOCATION_HARDWARE,
Manifest.permission.ACCESS_COARSE_LOCATION
).withListener(new MultiplePermissionsListener() {
@Override public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */}
@Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */}
}).check();
MultiplePermissionsListener dialogMultiplePermissionsListener =
DialogOnAnyDeniedMultiplePermissionsListener.Builder
.withContext(getApplicationContext())
.withTitle("INTERNET and GPS permission")
.withMessage("Both permissions are needed to help you better")
.withButtonText(android.R.string.ok)
.build();
MultiplePermissionsListener snackbarMultiplePermissionsListener =
SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
.with(view, "Camera and audio access is needed to take pictures of your dog")
.withOpenSettingsButton("Settings")
.withCallback(new Snackbar.Callback() {
@Override
public void onShown(Snackbar snackbar) {
// Event handler for when the given Snackbar is visible
}
@Override
public void onDismissed(Snackbar snackbar, int event) {
// Event handler for when the given Snackbar has been dismissed
}
})
.build();
String apiKey = getString(R.string.api_key);
if(apiKey.isEmpty()){
Log.d("Error","no api key found");
return;
}
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), apiKey);
}
PlacesClient placesClient = Places.createClient(this);
initAutoCompleteTextView()
}
private void initAutoCompleteTextView() {
autoCompleteTextView = findViewById(R.id.auto);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setOnItemClickListener(autocompleteClickListener);
adapter = new AutoCompleteAdapter(this, placesClient);
autoCompleteTextView.setAdapter(adapter);
}
private AdapterView.OnItemClickListener autocompleteClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
try {
final AutocompletePrediction item = adapter.getItem(i);
String placeID = null;
if (item != null) {
placeID = item.getPlaceId();
}
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS
, Place.Field.LAT_LNG);
FetchPlaceRequest request = null;
if (placeID != null) {
request = FetchPlaceRequest.builder(placeID, placeFields)
.build();
}
if (request != null) {
placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
@SuppressLint("SetTextI18n")
@Override
public void onSuccess(FetchPlaceResponse task) {
Log.d("TAG",task.getPlace().getName() + "\n" + task.getPlace().getAddress());
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
Log.d("TAG", Objects.requireNonNull(e.getMessage()));
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Autocompleteadapter
public class AutoCompleteAdapter extends ArrayAdapter<AutocompletePrediction> implements Filterable {
private ArrayList<AutocompletePrediction> mResultList;
private PlacesClient placesClient;
AutoCompleteAdapter(Context context, PlacesClient placesClient) {
super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
this.placesClient = placesClient;
}
@Override
public int getCount() {
return mResultList.size();
}
@Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull 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);
if (item != null) {
textView1.setText(item.getPrimaryText(null));
textView2.setText(item.getSecondaryText(null));
}
return row;
}
@NonNull
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
// We need a separate list to store the results, since
// this is run asynchronously.
ArrayList<AutocompletePrediction> filterData = new ArrayList<>();
// Skip the autocomplete query if no constraints are given.
if (charSequence != null) {
// Query the autocomplete API for the (constraint) search string.
filterData = getAutocomplete(charSequence);
}
results.values = filterData;
if (filterData != null) {
results.count = filterData.size();
} else {
results.count = 0;
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
mResultList = (ArrayList<AutocompletePrediction>) results.values;
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
@Override
public CharSequence convertResultToString(Object resultValue) {
// Override this method to display a readable result in the AutocompleteTextView
// when clicked.
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
//Create a RectangularBounds object.
RectangularBounds bounds = RectangularBounds.newInstance(
new LatLng(-33.880490, 151.184363),
new LatLng(-33.858754, 151.229596));
final FindAutocompletePredictionsRequest.Builder requestBuilder =
FindAutocompletePredictionsRequest.builder()
.setQuery(constraint.toString())
.setCountry("") //Use only in specific country
// Call either setLocationBias() OR setLocationRestriction().
.setLocationBias(bounds)
// .setLocationRestriction(bounds)
.setSessionToken(AutocompleteSessionToken.newInstance())
.setTypeFilter(TypeFilter.ADDRESS);
Task<FindAutocompletePredictionsResponse> results =
placesClient.findAutocompletePredictions(requestBuilder.build());
//Wait to get results.
try {
Tasks.await(results, 60, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
e.printStackTrace();
}
if (results.isSuccessful()) {
if (results.getResult() != null) {
return (ArrayList<AutocompletePrediction>) results.getResult().getAutocompletePredictions();
}
return null;
} else {
return null;
}
}
}
Logcat экстракт
2020-02-07 23:22:45.397 31414-31414/? W/le.trip_planne: OatFileAssistant(/data/app/com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==/split_lib_slice_7_apk.apk) Oat_file does not exist, will fallback to the original dex/jar file
2020-02-07 23:22:45.398 31414-31414/? W/le.trip_planne: Generation of oat file /data/dalvik-cache/arm64/data@app@com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==@split_lib_slice_8_apk.apk@classes.dex not attempted because the vdex file /data/dalvik-cache/arm64/data@app@com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==@split_lib_slice_8_apk.apk@classes.vdex could not be opened.
2020-02-07 23:22:45.398 31414-31414/? W/le.trip_planne: OatFileAssistant(/data/app/com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==/split_lib_slice_8_apk.apk) Oat_file does not exist, will fallback to the original dex/jar file
2020-02-07 23:22:45.400 31414-31414/? W/le.trip_planne: Generation of oat file /data/dalvik-cache/arm64/data@app@com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==@split_lib_slice_9_apk.apk@classes.dex not attempted because the vdex file /data/dalvik-cache/arm64/data@app@com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==@split_lib_slice_9_apk.apk@classes.vdex could not be opened.
2020-02-07 23:22:45.400 31414-31414/? W/le.trip_planne: OatFileAssistant(/data/app/com.example.trip_planner-rCbuIqxurZyXjkzsSKQxbQ==/split_lib_slice_9_apk.apk) Oat_file does not exist, will fallback to the original dex/jar file
2020-02-07 23:22:45.403 31414-31414/? W/le.trip_planne: JIT profile information will not be recorded: profile file does not exits.
2020-02-07 23:22:45.404 31414-31414/? I/chatty: uid=10364(com.example.trip_planner) identical 10 lines
2020-02-07 23:22:45.404 31414-31414/? W/le.trip_planne: JIT profile information will not be recorded: profile file does not exits.
2020-02-07 23:22:45.418 31414-31414/? I/Perf: Connecting to perf service.
2020-02-07 23:22:45.526 31414-31414/? I/InstantRun: starting instant run server: is main process
2020-02-07 23:22:45.533 31414-31414/? V/Font: Change font:1
2020-02-07 23:22:45.533 31414-31414/? V/Font: Default family:android.graphics.Typeface@f0100b4
2020-02-07 23:22:45.537 31414-31441/? E/Perf: Fail to get file list com.example.trip_planner
2020-02-07 23:22:45.538 31414-31441/? E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-02-07 23:22:45.538 31414-31441/? E/Perf: Fail to get file list com.example.trip_planner
2020-02-07 23:22:45.538 31414-31441/? E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-02-07 23:22:45.603 31414-31414/? V/FlingOptimizerScroller: FlingOptimizerOverScroller Init
2020-02-07 23:22:45.624 31414-31414/? W/le.trip_planne: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-02-07 23:22:45.624 31414-31414/? W/le.trip_planne: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-02-07 23:22:45.773 31414-31414/? V/ViewRootImpl: The specified message queue synchronization barrier token has not been posted or has already been removed
2020-02-07 23:22:45.796 31414-31437/? D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@7943d0[MainActivity]
2020-02-07 23:22:45.797 31414-31442/? I/AdrenoGLES: QUALCOMM build : bc92c36, I9e73322269
Build Date : 08/28/19
OpenGL ES Shader Compiler Version: EV031.27.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.8.1.R1.09.00.00.529.074
Remote Branch : NONE
Reconstruct Branch : NOTHING
2020-02-07 23:22:45.797 31414-31442/? I/AdrenoGLES: Build Config : S P 8.0.8 AArch64
2020-02-07 23:22:45.800 31414-31442/? I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000
2020-02-07 23:22:45.812 31414-31442/? W/Gralloc3: mapper 3.x is not supported
2020-02-07 23:22:45.856 31414-31414/? W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@c82a7fb
2020-02-07 23:22:45.879 31414-31414/? V/ViewRootImpl: The specified message queue synchronization barrier token has not been posted or has already been removed
2020-02-07 23:22:45.909 31414-31414/? W/Choreographer: Already have a pending vsync event. There should only be one at a time.
2020-02-07 23:22:46.024 31414-31414/? D/OnePlusJankManager: Chor uploadMDM JANK_TYPE_ONCE mViewTitle = com.example.trip_planner/com.example.trip_planner.MainActivity--- jank level = 1
2020-02-07 23:22:46.097 31414-31437/? D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@7943d0[MainActivity]
2020-02-07 23:22:51.209 31414-31414/com.example.trip_planner I/AssistStructure: Flattened final assist data: 2048 bytes, containing 1 windows, 11 views
2020-02-07 23:22:51.223 31414-31414/com.example.trip_planner E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2020-02-07 23:22:51.228 31414-31414/com.example.trip_planner I/chatty: uid=10364(com.example.trip_planner) identical 2 lines
2020-02-07 23:22:51.228 31414-31414/com.example.trip_planner E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2020-02-07 23:23:15.867 31414-31432/com.example.trip_planner D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@7943d0[MainActivity]
2020-02-07 23:23:16.943 31414-31554/com.example.trip_planner W/Filter: An exception occured during performFiltering()!
java.lang.NullPointerException: Attempt to invoke interface method 'com.google.android.gms.tasks.Task com.google.android.libraries.places.api.net.PlacesClient.findAutocompletePredictions(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest)' on a null object reference
at com.example.trip_planner.AutoCompleteAdapter.getAutocomplete(AutoCompleteAdapter.java:141)
at com.example.trip_planner.AutoCompleteAdapter.access$000(AutoCompleteAdapter.java:29)
at com.example.trip_planner.AutoCompleteAdapter$1.performFiltering(AutoCompleteAdapter.java:82)
at android.widget.Filter$RequestHandler.handleMessage(Filter.java:236)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:67)
2020-02-07 23:23:20.485 31414-31562/com.example.trip_planner W/Filter: An exception occured during performFiltering()!
java.lang.NullPointerException: Attempt to invoke interface method 'com.google.android.gms.tasks.Task com.google.android.libraries.places.api.net.PlacesClient.findAutocompletePredictions(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest)' on a null object reference
at com.example.trip_planner.AutoCompleteAdapter.getAutocomplete(AutoCompleteAdapter.java:141)
at com.example.trip_planner.AutoCompleteAdapter.access$000(AutoCompleteAdapter.java:29)
at com.example.trip_planner.AutoCompleteAdapter$1.performFiltering(AutoCompleteAdapter.java:82)
at android.widget.Filter$RequestHandler.handleMessage(Filter.java:236)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:67)
2020-02-07 23:23:20.936 31414-31562/com.example.trip_planner W/Filter: An exception occured during performFiltering()!
java.lang.NullPointerException: Attempt to invoke interface method 'com.google.android.gms.tasks.Task com.google.android.libraries.places.api.net.PlacesClient.findAutocompletePredictions(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest)' on a null object reference
at com.example.trip_planner.AutoCompleteAdapter.getAutocomplete(AutoCompleteAdapter.java:141)
at com.example.trip_planner.AutoCompleteAdapter.access$000(AutoCompleteAdapter.java:29)
at com.example.trip_planner.AutoCompleteAdapter$1.performFiltering(AutoCompleteAdapter.java:82)
at android.widget.Filter$RequestHandler.handleMessage(Filter.java:236)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:67)