在Horizo​​ntalListView项目中单击时,Youtube视频未停止

时间:2017-08-06 09:52:00

标签: android video onclick youtube-api

我正在使用Youtube Data API来访问视频。我成功地在ListView上显示缩略图图像。当我启动应用程序时,单击列表项之一,它在视频应该播放的容器上加载。我有问题,当我点击下一个缩略图,然后下一个视频没有显示。我检查登录索引,位置已更改但视频未加载。我不知道我在哪里做错了?< / p>

这与我的问题相同,但无法解决此问题How to refresh Youtube Player View onItemClickListener() in a ListView

FragmentVideoDestination

public class FragmentVideoDestination extends Fragment {

    private FragmentActivity myContext;

    YouTubePlayer YPlayer;
    private static final String YoutubeDeveloperKey = "AIzaSyCLk_SWbZseee8lpSEb6rLTSvhL8YSLjEE";
    String Navigation_URL_Popular_Destination_video = "http://192.168.100.7:1337/api/popular_destinations";
    HorizontalListView horizontalListView;
    FrameLayout framelayoutvideo;


    String video_Id;

    String thumbnail_image;
    String[] youtube_video_url;
    String parsed_url;
    ArrayList<ClassDestinationFragmentYoutubeVideo> destination_list_grid_vieo = new ArrayList<>();

    @Override
    public void onAttach(Activity activity) {

        if (activity instanceof FragmentActivity) {
            myContext = (FragmentActivity) activity;
        }

        super.onAttach(activity);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.destination_grid_detail_video, container, false);
//        YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
//        FragmentTransaction transaction = getFragmentManager().beginTransaction();
//        transaction.replace(R.id.youtubeFragment, youTubePlayerFragment).commit();
        //youTubePlayerFragment = (YouTubePlayerSupportFragment) getSupport().findFragmentById(R.id.youtubeFragment);

////
        horizontalListView = (HorizontalListView) view.findViewById(R.id.horizontal_scroll_list_item);
        framelayoutvideo = (FrameLayout) view.findViewById(R.id.youtubeFragment);
        final YouTubePlayerSupportFragment youTubePlayerFragment = new YouTubePlayerSupportFragment();
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.relative_layout_destination_video, youTubePlayerFragment);
        fragmentTransaction.commit();


        makeJsonPopularDestinationDetailPageVideo();


        horizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                video_Id = destination_list_grid_vieo.get(position).getUrl();
                System.out.println("position" + destination_list_grid_vieo.get(position).getUrl());
                if (YPlayer != null) {
                    //YPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                    YPlayer.loadVideo(video_Id);
                    //YPlayer.play();
                }


            }
        });


        youTubePlayerFragment.initialize(YoutubeDeveloperKey, new OnInitializedListener() {


            @Override
            public void onInitializationSuccess(Provider provider, YouTubePlayer youTubePlayer, boolean b) {

                //youTubePlayer.setShowFullscreenButton(false);
                if (youTubePlayer != null) {
                    if (!b) {


                        // System.out.println("POsition" + destination_list_grid_vieo.get(0).getUrl());
                        //youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                        youTubePlayer.loadVideo(destination_list_grid_vieo.get(0).getUrl());
                        // youTubePlayer.loadVideo("Hc97uvxJTNQ");


                        YPlayer = youTubePlayer;
                        // youTubePlayer.play();

                    }
                }


            }


            @Override
            public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
                String errorMessage = arg1.toString();
                Toast.makeText(getContext(), errorMessage, Toast.LENGTH_LONG).show();
                Log.d("errorMessage:", errorMessage);

            }


        });
















/*
        horizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                System.out.println("position" + destination_list_grid_vieo.get(position).getUrl());
                video_Id = destination_list_grid_vieo.get(position).getUrl();

             //   Picasso.with(getContext()).load(destination_list_grid.get(position).getOther_images()).into(imageViewPager);



                youTubePlayerFragment.initialize(YoutubeDeveloperKey, new OnInitializedListener() {
                    @Override
                    public void onInitializationSuccess(Provider provider, YouTubePlayer youTubePlayer, boolean b) {

                        youTubePlayer.setShowFullscreenButton(false);

                        if (!b) {

                            youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);

                            youTubePlayer.cueVideo(video_Id); // youTubePlayer.play();
                            YPlayer = youTubePlayer;

                        }


                    }


                    @Override
                    public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {


                    }




                });

            }
        });   */


        return view;

    }


    private void makeJsonPopularDestinationDetailPageVideo() {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_Popular_Destination_video + "/1";

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {


                            //
                            JSONObject jsonObject = new JSONObject(response);

                            JSONArray jArray = new JSONArray();

                            jArray = jsonObject.getJSONArray("videos");

                            for (int i = 0; i < jArray.length(); i++) {

                                JSONObject jsonObjectinner = jArray.getJSONObject(i);
                                thumbnail_image = jsonObjectinner.getString("thumbnail");
                                //  youtube_video_url = jsonObjectinner.getString("url").substring(32, 43);
                                youtube_video_url = String.valueOf(jsonObjectinner.getString("url")).split("=");
                                parsed_url = youtube_video_url[1];


                                destination_list_grid_vieo.add(new ClassDestinationFragmentYoutubeVideo(thumbnail_image, parsed_url));
                                System.out.println("Destination list" + destination_list_grid_vieo.get(i).getUrl());
                            }


                            PopularDestinationGridVideAdapter popularDestinationGridVideAdapter = new PopularDestinationGridVideAdapter(getContext(), destination_list_grid_vieo);
//                            popularDestinationGridVideAdapter.notifyDataSetChanged();
                            System.out.println("Grid" + destination_list_grid_vieo);
                            horizontalListView.setAdapter(popularDestinationGridVideAdapter);


                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                //  headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }

        };


        requestQueue.add(stringRequest);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        YPlayer = null;
    }
}

PopularDestinationGridVideAdapter

public class PopularDestinationGridVideAdapter extends BaseAdapter {

    Context mContext;
    ArrayList<ClassDestinationFragmentYoutubeVideo> class_destination_youtube_video = null;
    String TAG = "HomeTab_adapter";


    public PopularDestinationGridVideAdapter(Context mContext, ArrayList<ClassDestinationFragmentYoutubeVideo> class_destination_youtube_video) {
        super();
        this.mContext = mContext;
        this.class_destination_youtube_video = class_destination_youtube_video;
    }

    @Override
    public int getCount() {

        return class_destination_youtube_video.size();
    }

    @Override
    public Object getItem(int position) {
        return class_destination_youtube_video.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Holder viewHolder;

        if (convertView == null) {
            // inflate the layout
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            convertView = inflater.inflate(R.layout.grid_pager_popular_destination_item, parent, false);

            // well set up the ViewHolder
            //  viewHolder = new ClassScheduleStudentAdapter.Holder();
            viewHolder = new Holder();

            // viewHolder.popular_destintion_id = (TextView) convertView.findViewById(R.id.student_profile_subject);
            viewHolder.view = (ImageView) convertView.findViewById(R.id.image_detail_page_item);


            //     Log.d(TAG, "@@ postion:" + position + " getTeacherName" + class_destination.get(position).getId());
            convertView.setTag(viewHolder);


        } else {
            // we've just avoided calling findViewById() on resource everytime
            // just use the viewHolder
            //  viewHolder = (ClassScheduleStudentAdapter.Holder) convertView.getTag();
            viewHolder = (Holder) convertView.getTag();
        }


        //  File f = new File(class_destination.get(position).getImagelogo());
        // Picasso.with(mContext).load(f).into(viewHolder.image_logo);

        Picasso.with(mContext).load(class_destination_youtube_video.get(position).getThumbnai()).error(R.drawable.close).into(viewHolder.view);

        return convertView;
    }

    class Holder {
        ImageView view;
    }


}

登录

08-10 10:29:46.708 16772-16772/org.municipality.mobile.patanheritage E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                       Process: org.municipality.mobile.patanheritage, PID: 16772
                                                                                       java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                                                                                           at java.util.ArrayList.get(ArrayList.java:411)
                                                                                           at org.municipality.mobile.patanheritage.fragment.FragmentVideoDestination$2.onInitializationSuccess(FragmentVideoDestination.java:139)
                                                                                           at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
                                                                                           at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source)
                                                                                           at com.google.android.youtube.player.internal.r.g(Unknown Source)
                                                                                           at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
                                                                                           at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
                                                                                           at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
                                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                                           at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
  

列表项目索引在日志中显示已更改,但运行视频未停止,并且在另一个列表项视频中被点击时启动新视频。如何解决此问题?

2 个答案:

答案 0 :(得分:1)

每次点击列表项时,您都在初始化播放器。它应该只进行一次,你不必使用  youTubePlayer.play(); 以下行将起作用 youTubePlayer.cueVideo(VIDEO_ID);

答案 1 :(得分:0)

public class FragmentVideoDestination extends Fragment {
    private FragmentActivity myContext;
    YouTubePlayer YPlayer;
    private static final String YoutubeDeveloperKey = "AIzaSyCLk_SWbZseee8lpSEb6rLTSvhL8YSLjEE";
    String Navigation_URL_Popular_Destination_video = "http://192.168.100.7:1337/api/popular_destinations";
    HorizontalListView horizontalListView;
    FrameLayout framelayoutvideo;
    String video_Id;
    String thumbnail_image;
    String[] youtube_video_url;
    String parsed_url;
    ArrayList<ClassDestinationFragmentYoutubeVideo> destination_list_grid_vieo = new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.destination_grid_detail_video, container, false);
        horizontalListView = (HorizontalListView) view.findViewById(R.id.horizontal_scroll_list_item);
        framelayoutvideo = (FrameLayout) view.findViewById(R.id.youtubeFragment);
        final YouTubePlayerSupportFragment youTubePlayerFragment = new YouTubePlayerSupportFragment();
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
       fragmentTransaction.replace(R.id.relative_layout_destination_video, youTubePlayerFragment);
        fragmentTransaction.commit();
        makeJsonPopularDestinationDetailPageVideo();
        horizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                video_Id = destination_list_grid_vieo.get(position).getUrl();
                System.out.println("position" + destination_list_grid_vieo.get(position).getUrl());
                if (YPlayer != null) {
                     YPlayer.cueVideo(video_Id); // youTubePlayer.play();
                }
            }
        });
        youTubePlayerFragment.initialize(YoutubeDeveloperKey, new OnInitializedListener() {
            @Override
            public void onInitializationSuccess(Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        if (!b) {
             YPlayer= youTubePlayer;
            if(video_Id!=null)
                         YPlayer.cueVideo(video_Id);
                    }
                }
            }
            @Override
            public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {

            }

        });
        return view;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    if (YPlayer!= null) {
            YPlayer.release();
            YPlayer  = null;
        }
    }

    private void makeJsonPopularDestinationDetailPageVideo() {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_Popular_Destination_video + "/1";

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {


                            //
                            JSONObject jsonObject = new JSONObject(response);

                            JSONArray jArray = new JSONArray();

                            jArray = jsonObject.getJSONArray("videos");

                            for (int i = 0; i < jArray.length(); i++) {

                                JSONObject jsonObjectinner = jArray.getJSONObject(i);
                                thumbnail_image = jsonObjectinner.getString("thumbnail");
                                //  youtube_video_url = jsonObjectinner.getString("url").substring(32, 43);
                                youtube_video_url = String.valueOf(jsonObjectinner.getString("url")).split("=");
                                parsed_url = youtube_video_url[1];
                                destination_list_grid_vieo.add(new ClassDestinationFragmentYoutubeVideo(thumbnail_image, parsed_url));
                                System.out.println("Destination list" + destination_list_grid_vieo.get(i).getUrl());
                            }


                            PopularDestinationGridVideAdapter popularDestinationGridVideAdapter = new PopularDestinationGridVideAdapter(getContext(), destination_list_grid_vieo);
                video_Id=destination_list_grid_vieo.get(0).getUrl();
                if(YPlayer!=null){
                YPlayer.cueVideo(video_Id);
                }
//                            popularDestinationGridVideAdapter.notifyDataSetChanged();
                            System.out.println("Grid" + destination_list_grid_vieo);
                            horizontalListView.setAdapter(popularDestinationGridVideAdapter);


                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                //  headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }
        };
        requestQueue.add(stringRequest);
    }
}

这可能对您有所帮助