在Horizo​​ntalListView项目中单击时,Youtube视频未停止 [英] Youtube Video is not Stopped when clicked in HorizontalListView Item

查看:88
本文介绍了在Horizo​​ntalListView项目中单击时,Youtube视频未停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Youtube Data API来访问视频.我已成功在ListView上显示缩略图.当我启动应用程序"并单击列表项"之一时,它将加载到应播放视频的容器上我遇到问题,当我单击下一个缩略图时,然后不显示下一个视频.我通过索引检查了日志,位置已更改,但未加载视频.我不知道我在哪里做错了?

I am using Youtube Data API to Access the Video.I am successful on Displaying the thumbnail image on the ListView.When i start Application,and Click the one of List Item, it Loads on the container where the Video should b played.I got issue ,when i Click the next thumbnail image ,then next Video is not Displayed .I Checked on Log through the index ,the position are Changed but Video is not Loaded.I don't know where i am Doing Wrong?

这与我的问题相同,但无法解决此问题

this is same as mine problem but not able to solve looking this 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)

列表项索引在日志中显示为已更改,但是在另一个列表项视频中单击后,正在运行的视频"未停止并启动新视频.如何解决此问题?

List Item index are shown changed in the Log but the Running Video is not stopped and Start the New Video When CLicked in the Another List Item Video.How can this issue be solved?

推荐答案

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);
    }
}

这可能对您有帮助

这篇关于在Horizo​​ntalListView项目中单击时,Youtube视频未停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆