Reputation: 59
I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance. 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(Fragment)
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
Upvotes: 1
Views: 86
Reputation: 59
Got the answer. there was a problem in sharing data between activity and fragment. the value was being set null twice, one before and one after the function call(i dont know why but). then instead of calling newInstance()
i used bundle, checked if it is null or not in fragment class and then set the value of 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. :)
Upvotes: 1
Reputation: 1605
In your CollegeGallery.java
in place of:
yt.newInstance(playid)
write this
YoutubeVideoList.newInstance(playid)
Also remove the static String id
from your YoutubeVideoList fragment if it's useless
Upvotes: 0