Home » Android » Synchronized loading of YoutubePlayerSupportFragment

Synchronized loading of YoutubePlayerSupportFragment

Posted by: admin November 1, 2017 Leave a comment

Questions:

I want to load a specific video each time I click a different menu from the navigation drawer. The id of the video is stored in the database. I am using Volley library for the same. Problem is that every time I toast I get id as blank and then id as actual id. Clearly fragment is loaded first. Is there any way I could make the youtubePlayer.cue(id) wait till the getData() fetches the id to cue the video?

I tried my luck with Thread.sleep(), synchronize etc but it did not work.

Here is the code:

String id;
void getData() {
        StringRequest stringRequest = new StringRequest(Config.TOPIC_URL+"?topic="+topic_name, new Response.Listener<String>() {
            @Override

            public void onResponse(String response) {
                showJSON(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }

 private void showJSON(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
            JSONObject testData = result.getJSONObject(0);
            id = testData.getString("url");
            Toast.makeText(this, id, Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
 @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        if(!b){
            //topic_name and the corresponding link from the database
           //this toast gets prints first
            Toast.makeText(this, id, Toast.LENGTH_LONG).show();
            //id remains as null I want to populate this id
            //even if I call getData() here still the id remains as null
            youTubePlayer.cueVideo(id.trim().toString());
        }
    }

    //calling
    getData();
    YouTubePlayerSupportFragment frag =
                (YouTubePlayerSupportFragment) 
    getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);
    frag.initialize(PlayerConfig.API_KEY, this);
Answers: