gpt4 book ai didi

java - Android 中的 Activity 到 Fragment 通信

转载 作者:行者123 更新时间:2023-12-01 16:28:48 24 4
gpt4 key购买 nike

我是第一次使用fragment。我正在尝试从我的 fragment 中获取 YouTube 的视频列表。我正在从 firebase 检索 youtube url 并从中提取播放列表 id。该播放列表 ID 作为参数传递给 fragment ,然后 fragment 会列出播放列表中存在的所有视频。我成功地检索了 fragment 中的播放列表 ID,但它在 url 中更改为 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( 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


最佳答案

得到答案了。 Activity 和 Fragment 之间共享数据时出现问题。该值被设置为 null 两次,一次在函数调用之前,一次在函数调用之后(我不知道为什么)。然后而不是调用 newInstance()我使用了bundle,检查fragment类中是否为null,然后设置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. :)

关于java - Android 中的 Activity 到 Fragment 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62090786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com