1
Guys, I’m picking up a bit with asynchronous request on Android. I’m requesting a list of states on JSON
, via OkHttp
, and turn into a ArrayList
states to be able to state ListView
. However, in every way I tried the request only ends after the creation of the Fragment
, thus, the ArrayList
as a parameter of adapter
to execute the setListAdapter
is empty. This way always generates NullPointerException
and I don’t know what to do.
I’m going to leave down my last code, I already got from an example here of the stack, but I did not get a positive result.
How do I receive the request correctly? If it is Synchronous the app will get stuck and I believe there should be a cool way to do.
Just follow the code. (Obs: use an interface to help logic, was the idea I saw here in the stack)
Fragment from 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 extending 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 I created (based on an example from here in the stack)
public interface AsyncResponse {
void processFinish(ArrayList<Estado> estados);
}
Ps: I have already debug a light and the method processFinish()
in the PesquisaEstado
is executed only after onActivityCreated()
, for this reason the state becomes empty and gives NullPointerException
.
From now on I appreciate any help!