Well, I'm getting a lot of asynchronous request on Android. I am requesting a list of states in JSON
, via OkHttp
, and transforming into ArrayList
states to be able to set states in ListView
. However, in all the ways I tried the request it only ends after the creation of Fragment
, so the ArrayList
that I set as the adapter
parameter to execute setListAdapter
is empty. That way, it always generates NullPointerException
and I'm not sure what to do.
I will leave below my last code, which I have already taken from an example here from the stack, but I did not get a positive result.
How do I receive the request correctly? If Synchronous the app will get stuck and I believe that it should have a legal way of doing.
Follow the code. (obs: I use an interface to help in logic, it was the idea I saw here in the stack)
Fragment of the list of states
public class PesquisaEstado extends ListFragment implements AsyncResponse {
private ArrayList<Estado> estados;
private ArrayAdapter<Estado> mAdapter;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new EstadosTask(this).execute();
mAdapter = new ArrayAdapter<>(getActivity(),
R.layout.item_list_pesquisa, estados);
setListAdapter(mAdapter);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void processFinish(ArrayList<Estado> estados) {
this.estados = estados;
}
}
Class that extends AsyncTask
public class EstadosTask extends AsyncTask<Void, Void, ArrayList<Estado>>{
public static final String URL =
"https://bitbucket.org/Jocsa/jsonauxiliaresotb/raw/1fa827f1179ee827d1bedcdaa4c5befbe7686057/Estados.json";
public AsyncResponse delegate = null;
public EstadosTask(AsyncResponse delegate){
this.delegate = delegate;
}
@Override
protected ArrayList<Estado> doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient();
client.setReadTimeout(10, TimeUnit.SECONDS);
client.setConnectTimeout(15, TimeUnit.SECONDS);
Request request = new Request.Builder().url(URL).build();
try {
Response response = client.newCall(request).execute();
Type listType = new TypeToken<ArrayList<Estado>>(){}.getType();
String json = response.body().string();
Gson gson = new Gson();
ArrayList<Estado> estados = gson.fromJson(json, listType);
return estados;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(ArrayList<Estado> estados) {
delegate.processFinish(estados);
}
}
Interface that I created (based on an example here of the stack)
public interface AsyncResponse {
void processFinish(ArrayList<Estado> estados);
}
Ps: I've done a light debug and the processFinish()
method in PesquisaEstado
only runs after onActivityCreated()
, so the state is empty and gives NullPointerException
.
Thanks in advance for any help!