Well, that, I have implemented an application with 3 tabs and I want to update all the tabs when clicking when it shows the cities in the dialogue, the fact is that it does not even show me the cities, I do not know what I'm doing wrong.
My adapter:
public class RegionsAutocompleteAdapter extends BaseAdapter implements Filterable {
private Context mContext;
private List<Prediction> resultList = new ArrayList<Prediction>();
public RegionsAutocompleteAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public Prediction getItem(int index) {
return resultList.get(index);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
}
((TextView) convertView.findViewById(android.R.id.text1)).setText(getItem(position).getDescription());
return convertView;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
/*
SEGUN LA DOCUMENTACIÓN DE ANDROID, ESTE MÉTODO NO SE INVOCA
EN EL HILO UI, POR LO QUE NO ES NECESARIO QUE EL PROGRAMADOR
SE ENCARGUE DE LA GESTIÓN DE LOS HILOS.
*/
@Override
protected FilterResults performFiltering(CharSequence constraint) {
//Resultado del filtrado.
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<Prediction> places = autoComplete(mContext, constraint.toString());
// Asignamos los valores recogidos al FilterResults
if (places != null ) {
filterResults.values = places;
filterResults.count = places.size();
} else {
filterResults.values = null;
filterResults.count = 0;
}
}
return filterResults;
}
/*
SEGUN LA DOCUMENTACIÓN DE ANDROID, ESTE MÉTODO SI SE INVOCA
EN EL HILO UI, Y RECIBE DEL MÉTODO ANTERIOR LOS RESULTADOS
A MOSTRAR. NO DEBEMOS TEMER UN FALLO DEL LOOPER POR INTENTAR
MODIFICAR LA UI DESDE OTRO HILO.
*/
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultList = (List<Prediction>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
/*
EN ESTE MÉTODO, LA PETICIÓN QUE HACEMOS ES SÍNCRONA, YA QUE
ANDROID SE ENCARGARÁ DE EJECUTARLO EN UN HILO INDEPENDIENTE
*/
private List<Prediction> autoComplete(Context context, String input) {
List<Prediction> result = null;
//Desde el contexto llegamos a nuestra clase Application
if (context instanceof Activity) {
Activity act = (Activity) context;
AutocompleteApp application =
(AutocompleteApp) act.getApplication();
Retrofit retrofit = application.getRetrofitGoogle();
//Obtenemos nuestra instancia "singleton" de Retrofit
//Retrofit retrofit = ((AutoCompleteApplication) act.getApplication()).getRetrofitGoogle();
//Creamos el API
IGoogleRegionsApi api = retrofit.create(IGoogleRegionsApi.class);
//Obtenemos la petición lista para realizarla
Call<Region> callAutoComplete = api.loadAutocompleteRegions(input);
try {
//La ejecutamos con execute
result = callAutoComplete.execute().body().getPredictions();
} catch (IOException e) {
//Gestión del error
Log.e("ERROR IO", e.getMessage());
//Devolvemos el resultad
}
}
return result;
}
My dialogue:
public class DialogoBusquedaFragment extends DialogFragment {
AutoCompleteTextView autoCompleteTextView;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_dialogo_busqueda, null);
autoCompleteTextView = (AutoCompleteTextView) v.findViewById(R.id.textView_dialogo_busqueda);
autoCompleteTextView.setAdapter(new RegionsAutocompleteAdapter(getContext()));
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Prediction prediction = (Prediction) adapterView.getItemAtPosition(i);
autoCompleteTextView.setText(prediction.getDescription());
DialogoBusquedaFragment.this.getDialog().cancel();
}
});
builder.setView(v);
builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
return builder.create();
}
}
Class to consume:
public class AutocompleteApp extends Application {
private static Retrofit retrofitGoogle, retrofitOpenWeather;
@Override
public void onCreate() {
super.onCreate();
Gson gson = new GsonBuilder()
.create();
retrofitGoogle = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(initHttp())
.build();
retrofitOpenWeather = new Retrofit.Builder()
.baseUrl("https://api.openweather.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
//Podemos crear un interceptor para cada caso que necesitemos
private static OkHttpClient initHttp() {
Interceptor interceptor = new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.httpUrl();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("location","37.380413,-6.007445")
.addQueryParameter("radius","50000")
.addQueryParameter("types", "(cities)")
.addQueryParameter("language","es_ES")
.addQueryParameter("key","AIzaSyArgRhpfCPo35NAixPkc3OaZAE03xWfTxo")
.build();
Request newRequest = chain.request().newBuilder()
.url(url)
.build();
return chain.proceed(newRequest);
}
};
OkHttpClient client = new OkHttpClient();
client.interceptors().add(interceptor);
return client;
}
public static Retrofit getRetrofitGoogle() {
return retrofitGoogle;
}
public static Retrofit getRetrofitOpenWeather() { return retrofitOpenWeather; }
}
Method created in the main class to show the dialog:
//Método para mostrar el diálogo de búsqueda
private void showSearchDialog() {
DialogFragment dialogFragment = new DialogoBusquedaFragment();
dialogFragment.show(getSupportFragmentManager(), "Dialogo");
dialogFragment.setCancelable(false);
}
Floating action button of the Main class:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showSearchDialog();
}
});
Interface:
public interface IGoogleRegionsApi {
@GET("maps/api/place/autocomplete/json")
Call<Region> loadAutocompleteRegions(@Query("input") String input);
}