Активность по фрагментации Общение в Android - PullRequest
1 голос
/ 29 мая 2020

Фрагмент использую впервые. Я пытаюсь получить список видео с YouTube, присутствующих в моем фрагменте. Я получаю URL-адрес YouTube из firebase и извлекаю из него идентификатор списка воспроизведения. Этот идентификатор списка воспроизведения передается в качестве параметра фрагменту, который затем перечисляет все видео, присутствующие в списке воспроизведения. Я успешно могу получить идентификатор списка воспроизведения во фрагменте, но он изменяется на null в URL-адресе. Любая помощь заметна. Заранее спасибо. 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


Ответы [ 2 ]

1 голос
/ 30 мая 2020

Получил ответ. возникла проблема с обменом данными между активностью и фрагментом. значение устанавливалось нулевым дважды, один до и один после вызова функции (я не знаю почему, но). затем вместо вызова newInstance() я использовал bundle, проверил, является ли он нулевым или нет в классе фрагмента, а затем установил значение id. CollgeGallery. java

            @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);
                String playid = getYoutubeVideoId(clg.getVideourls());
                //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
                setPlayid(playid);
                Bundle bun = new Bundle();
                YoutubeVideoList firstfrag = new YoutubeVideoList();
                bun.putString("test", playid);
                firstfrag.setArguments(bun);
                getSupportFragmentManager().beginTransaction().add(R.id.youtube_frag, firstfrag).commit();
//                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
//                tr.add(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }```
**YoutubeVideoList.java**

    ```@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle args = this.getArguments();
            if(args != null){
                id = args.getString("test");
            }
        }```

Thanks everyone for your help. :)

0 голосов
/ 29 мая 2020

В вашем CollegeGallery.java вместо: yt.newInstance(playid) напишите это YoutubeVideoList.newInstance(playid)

Также удалите static String id из фрагмента YoutubeVideoList, если он бесполезен

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...