我是第一次使用片段。我正在尝试从片段中获取来自youtube的视频列表。我正在从Firebase检索YouTube网址,并从中提取播放列表ID。该播放列表ID作为参数传递给片段,然后片段将列出播放器中存在的所有视频。我可以成功检索片段中的播放列表ID,但网址中的ID更改为null。任何帮助都是可取的。在此先感谢。
CollegeGallery.java

    public CollegeImageGrid imagegrid;
    private static final String TAG = "CollegeGallery";
    public GridView grid_image, grid_video;
    public DatabaseReference ref;
    private String collegeid;
    private TextView moreimages, morevideos;
    private String playlistid;

    public void setPlayid(String playlistid) {
        this.playlistid = playlistid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_college_gallery);

        ref = FirebaseDatabase.getInstance().getReference("collegedata");
        //this will get the data from previous intent
        collegeid = getIntent().getStringExtra("gallery");
        grid_image = findViewById(R.id.grid_image);
//        grid_video = findViewById(R.id.grid_video); //for grid view of videos

        moreimages = findViewById(R.id.more_images);
        morevideos = findViewById(R.id.more_videos);

        //a list of string will  be passed to  imagegrid object
        ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                YoutubeVideoList yt = new YoutubeVideoList();
                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
                tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
            }
        });

        moreimages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
                image_in.putExtra("image",collegeid);
                startActivity(image_in);
            }
        });

        //will take to activity with only playlist video list fragment
        morevideos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
            }
        });

    }

    //function to extract playlist id
    public static String getYoutubeVideoId(String youtubeUrl) {
        String video_id = "";
        if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {

            String expression = "^.*?(?:list)=(.*?)(?:&|$)";

            CharSequence input = youtubeUrl;
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                String groupIndex1 = matcher.group(1);
                video_id = groupIndex1;
            }
        }
        return video_id;
    }

}


YoutubeVideoList.java(片段)


    private static String ARG_Param1;
    private static String id;
    List<YoutubeVideoModel> vids;
    Button btn;
    YoutubeAdapter adapter;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager manager;
    String mparam1;

    public YoutubeVideoList() {
    }

    //retrieving playlist id from the previous activity
    public static YoutubeVideoList newInstance(String id) {
        YoutubeVideoList yt = new YoutubeVideoList();
        Bundle args = new Bundle();
        args.putString(ARG_Param1, id);
        yt.setArguments(args);
        return yt;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mparam1 = getArguments().getString(ARG_Param1);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
    }

    @Override
    public  void onViewCreated(View container, Bundle savedInstanceState) {
        super.onViewCreated(container, savedInstanceState);
        recyclerView = container.findViewById(R.id.vidReclycer);
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(false);


         id = mparam1;
        //right here, id has the playlist id
        System.out.println("this is the playlist id------------------->"+id);
        String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
        //even url has the value but the list is not shown and id changes to null
        System.out.println(url);
        RequestQueue queue = Volley.newRequestQueue(getContext());

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        vids = new ArrayList<>();
                        try {
                            JSONObject mainObject = new JSONObject(response);
                            JSONArray itemArray = (JSONArray) mainObject.get("items");
                            for (int i = 0; i < itemArray.length(); i++) {
                                String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
                                String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
                                String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
                                YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
                                vids.add(vid);
                            }
                            adapter = new YoutubeAdapter(getContext(), vids);
                            recyclerView.setAdapter(adapter);
                            recyclerView.getAdapter().notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                Log.e("Error in request", error.getMessage());
            }
        });
        queue.add(request);
        }
    }
```this is the image of my logcat. It prints id and url as required, but then it changes to null


最佳答案

在您的CollegeGallery.java代替:
yt.newInstance(playid)
写这个
YoutubeVideoList.newInstance(playid)

如果没有用,还请从YoutubeVideoList片段中删除static String id

09-11 21:14