在Android中的Activity到Fragment的通信

huangapple go评论67阅读模式
英文:

Activity to fragment Communication in Android

问题

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);
        }
    }
英文:

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 = &quot;CollegeGallery&quot;;
    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(&quot;collegedata&quot;);
        //this will get the data from previous intent
        collegeid = getIntent().getStringExtra(&quot;gallery&quot;);
        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, &quot;No images&quot;, 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(&quot;image&quot;,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 = &quot;&quot;;
        if (youtubeUrl != null &amp;&amp; youtubeUrl.trim().length() &gt; 0 &amp;&amp; youtubeUrl.startsWith(&quot;http&quot;)) {

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

            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&lt;YoutubeVideoModel&gt; 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(&quot;this is the playlist id-------------------&gt;&quot;+id);
String url = &quot;https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&amp;playlistId=&quot;+id+&quot;&amp;part=snippet&amp;maxResults=36&quot;;
//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&lt;String&gt;() {
@Override
public void onResponse(String response) {
vids = new ArrayList&lt;&gt;();
try {
JSONObject mainObject = new JSONObject(response);
JSONArray itemArray = (JSONArray) mainObject.get(&quot;items&quot;);
for (int i = 0; i &lt; itemArray.length(); i++) {
String title = itemArray.getJSONObject(i).getJSONObject(&quot;snippet&quot;).getString(&quot;title&quot;);
String url = itemArray.getJSONObject(i).getJSONObject(&quot;snippet&quot;).getJSONObject(&quot;thumbnails&quot;).getJSONObject(&quot;maxres&quot;).getString(&quot;url&quot;);
String vidid = itemArray.getJSONObject(i).getJSONObject(&quot;snippet&quot;).getJSONObject(&quot;resourceId&quot;).getString(&quot;videoId&quot;);
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(&quot;Error in request&quot;, 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
</details>
# 答案1
**得分**: 1
收到答案。在活动和片段之间共享数据时出现了问题。该值在函数调用之前和之后分别被设置为 null,我不知道为什么会这样。然后我使用了 bundle,而不是调用 ```newInstance()```,在片段类中检查它是否为 null,然后设置 id 的值。
**CollgeGallery.java**
```ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// 获取 College 类的对象以获取 getImageurls(),其中包含 url 列表
College clg = dataSnapshot.getValue(College.class);
String playid = getYoutubeVideoId(clg.getVideourls());
// 将列表设置到 imagegrid,从此活动传递 url 到 imageview
imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
// 将适配器与 url 列表一起设置到网格
grid_image.setAdapter(imagegrid); // 检查错误,getCount 为空,导致应用崩溃
// 提取播放列表 id
//                String playid = getYoutubeVideoId(clg.getVideourls());
// 片段代码
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");
}
}```
感谢大家的帮助。 :)
<details>
<summary>英文:</summary>
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**
```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);
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(&quot;test&quot;, 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(&quot;test&quot;);
}
}```
Thanks everyone for your help. :)
</details>
# 答案2
**得分**: 0
在你的 `CollegeGallery.java` 中,将以下代码中的:
```yt.newInstance(playid)```
替换为:
```YoutubeVideoList.newInstance(playid)```
同时,如果在你的 `YoutubeVideoList` 片段中 `static String id` 是无用的话,请将其移除。
<details>
<summary>英文:</summary>
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&#39;s useless
</details>

huangapple
  • 本文由 发表于 2020年5月30日 00:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/62090786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定