0

my app call the api to get Pokemon information(includes id) successfully then in the second call id become zero and the response give me 404 error(No Pokemon has id=0).

The id is public static int declared directly at the top of PokemonActivity, load & Descriptionload both get called in onCreate() method.. after debugging i found sometimes the description loaded but it's the previous requested Pokemon description or before the previous etc.. also when i open the same Pokemon many times it shows the correct description

public void load() {
    //... first api call to get pokemon details
    id = response.getInt("id");
    // ... 
}
public void Descriptionload() {
    desUrl = "https://pokeapi.co/api/v2/pokemon-species/" + id + "/";
    JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, desUrl, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {           
                    descriptionTextView.setText(response.getJSONArray("flavor_text_entries").getJSONObject(0).getString("flavor_text"));
                } catch (JSONException e) {
                    Log.e("cs50", "Pokemon description json error", e);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("cs50", "Pokemon description details error");
            }
        });
        requestQueue.add(request2);
    }

full PokemonActivity: https://dpaste.org/HF4Z

Pokadex: https://cs50.harvard.edu/x/2020/tracks/mobile/android/pokedex/

0

Asynchronicity

when the app make the first call it will continue before it get response and begin the second API call ,, Solution: implement a call back for the volley response.

  1. declare this interface in the activity
public interface VolleyCallBack {
        void onSuccess();
    }
  1. change load() like this:
public void load(final VolleyCallBack callBack) {
    //... first API call to get Pokemon details
    id = response.getInt("id");
    callBack.onSuccess();
    // ... 
}
  1. call load & Descriptionload like this:
load(new VolleyCallBack() {
            @Override
            public void onSuccess() {
                Descriptionload();
            }
        });

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .