Sam K.
Sam K.

Reputation: 31

RecyclerView in Fragment implementation

I have successfully implemented a RecyclerView in a regular Activity (not a Fragment), my issue within the Fragment is that the PostsList doesn't seem to be populated in the OnViewCreated() method (The arraySize is 0). However when I log the PostsList array size from within the getPosts() JSON method, the array size is being logged correctly.

It seems like the PostsList isn't being populated when I call it from the OnViewCreated().

What is the issue and how can I solve it so I can send the postsList to a RecyclerView adapter?

Fragment:

{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;



    RecyclerView recyclerView;
    ArrayList<Post> PostsList = new ArrayList<>();
    String userId = "4b248ae2-7d0d-47f6-bc01-3c6ee12cb10e";


    public void nameClicked(View view){
        Log.i("NAME", "name Clicked");
    }


    public Tab2() {

    }


    // TODO: Rename and change types and number of parameters
    public static Tab2 newInstance(String param1, String param2) {
        Tab2 fragment = new Tab2();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }



    }

    public void getPosts(String id) {



        String url = "http://10.0.2.2:5000/api/posts/postf?id="+id;
        RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
        JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray ja) {
                        try {
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject o = ja.getJSONObject(i);
                                int id = Integer.parseInt(o.getString("id"));
                                String text = o.getString("text");
                                String applicationUserId = o.getString("applicationUserId");
                                String image = o.getString("image");
                                int likes = Integer.parseInt(o.getString("likes"));
                                String date = o.getString("dateTime");
                                double latitude =Double.parseDouble(o.getString("latitude"));
                                double longitude =Double.parseDouble(o.getString("latitude"));
                                String locatonImage = o.getString("locationImage");

                                PostsList.add(new Post(id, text,applicationUserId,image,likes,date,latitude,longitude,locatonImage));

                                Log.i("length",Integer.toString(PostsList.size()));

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("error errrrrrrr", error.toString());
                    }
                });
        queue.add(jsonRequest);



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tab2, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getPosts("4b248ae2-7d0d-47f6-bc01-3c6ee12cb10e");
        recyclerView = view.findViewById(R.id.recyclerView);
        FeedAdapter myAdapter = new FeedAdapter(view.getContext(),PostsList);
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        Log.i("ArrayLength", Integer.toString(PostsList.size()));



    }


    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

Upvotes: 0

Views: 61

Answers (3)

Kennedy
Kennedy

Reputation: 557

1.Why don't you just do all you need to in onCreateView? and add a
@NonNull to the LayoutInflater

2.I don't see where you populated the adapter(recyclerView.setAdapter(adapter);) in your volley function

Set the following parameters as seen below, delete your onViewCreated and replace your onCreateView with the one in this answer

// the fragment initialization parameters
private RecyclerView recyclerView;
FeedAdapter myAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<Post> PostsList;


@Override
    public View onCreateView(NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_tab2, container, false);


        recyclerView = root.findViewById(R.id.recyclerView);
        myAdapter = new FeedAdapter(getContext(),PostsList);
        recyclerView.setAdapter(myAdapter);
        Log.i("ArrayLength", Integer.toString(PostsList.size()));

mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(mLayoutManager);

        //initializing the postlist
        PostsList = new ArrayList<>();
        getPosts("4b248ae2-7d0d-47f6-bc01-3c6ee12cb10e");

      return root;  
    }

Then replace your for loop with this, and your adapter should be populated

    for (int i = 0; i < ja.length(); i++) {
    JSONObject o = ja.getJSONObject(i);
    int id = Integer.parseInt(o.getString("id"));
    String text = o.getString("text");
    String applicationUserId = o.getString("applicationUserId");
    String image = o.getString("image");
    int likes = Integer.parseInt(o.getString("likes"));
    String date = o.getString("dateTime");
    double latitude =Double.parseDouble(o.getString("latitude"));
    double longitude =Double.parseDouble(o.getString("latitude"));
    String locatonImage = o.getString("locationImage");

    PostsList.add(new Post(id, text,applicationUserId,image,likes,date,latitude,longitude,locatonImage));
FeedAdapter adapter = new FeedAdapter(getActivity(),PostsList); // initialise the adapter
recyclerView.setAdapter(adapter); // set the recycler view to the adapter
adapter.notifyDataSetChanged();  // notify the adapter of the change

    Log.i("length",Integer.toString(PostsList.size()));

    }

Upvotes: 1

Asad Mahmood
Asad Mahmood

Reputation: 636

first, you should declare FeedAdapter as global variable, like:

FeedAdapter myAdapter;

then, in onViewCreated method first initialize FeedAdapter

    myAdapter = new FeedAdapter(view.getContext(),PostsList);
    recyclerView.setAdapter(myAdapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
    getPosts("4b248ae2-7d0d-47f6-bc01-3c6ee12cb10e");

and in getPosts method call notifyDataSetChanged() method after forloop:

 for (int i = 0; i < ja.length(); i++) {
                                JSONObject o = ja.getJSONObject(i);
                                int id = Integer.parseInt(o.getString("id"));
                                String text = o.getString("text");
                                String applicationUserId = o.getString("applicationUserId");
                                String image = o.getString("image");
                                int likes = Integer.parseInt(o.getString("likes"));
                                String date = o.getString("dateTime");
                                double latitude =Double.parseDouble(o.getString("latitude"));
                                double longitude =Double.parseDouble(o.getString("latitude"));
                                String locatonImage = o.getString("locationImage");

                                PostsList.add(new Post(id, text,applicationUserId,image,likes,date,latitude,longitude,locatonImage));

                                Log.i("length",Integer.toString(PostsList.size()));

                            }


myAdapter.notifyDataSetChanged()

Upvotes: 0

C&#244;ng Hải
C&#244;ng Hải

Reputation: 5241

You should call recyclerView.getAdapter().notifyDataSetChanged() after add list item outside loop when get api successfully.

Upvotes: 0

Related Questions