0

enter image description here This is what I am getting with the help Sultan Mahmud help(he has posted below in the comment) . But from the code posted here I just get blank layout This is what I want enter image description here I am trying to read the data from the JSON and parse them in android layout. The basic idea of this overall is I am trying to group the items by date. This means all the events occurred during that particular date is listed below it and that date is listed as a header.

I also added the print statement inside JSON method to see whether the objects are added to it or not. And it turns out the object is added to the list. There might be some issue of setting the adapter or the way to call the adapter in JSON. Not sure though

For this, I got the help from this post Divide elements on groups in RecyclerView or Grouping Recyclerview items ,say by date

I tried it with dummy data and it works fine. But when I read it from JSON file and trying to adopt in android I might have done some mistake.

What I am doing is parseJSOn method is creating the object and adding into the ArrayList. And that ArrayList is passed into the hashmap? Is this the way to do? I have seen lots of tutorials posted about JSON parsing, but haven't really got the idea how to do when there are multiple view types in my case header and events

Also, Can anyone help me how to implement onclick listener recycler view in my case? (In most of the case model is passed as reference for getting the position. so what would be in mine case?

I have posted the code with an explanation. Any help is appreciated

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Adapter;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import static java.util.stream.Collectors.toMap;

public class MainActivity extends AppCompatActivity {


    @NonNull
    private List<StreamItem> myOptions = new ArrayList<>();

    /*
     In this we have collection of list of header and Event it means for each date
     list of events are added. I have two layout of them one of header and one for event.

     */
    List<ListItem> consolidatedList = new ArrayList<>();


    private RecyclerView mRecyclerView;
    private StreamArrayAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);

        /*
        what I am doing is I am calling the parsJSON method what it does is it create the object for my model and add them in list
         */

        parseJSON();

        /*
        This the dummy data I tried it word as fine and group the datas by date
         */

       /* myOptions.add(new StreamItem("name 1", "2016-06-21"));
        myOptions.add(new StreamItem("name 2", "2016-06-05"));
        myOptions.add(new StreamItem("name 2", "2016-06-05"));
        myOptions.add(new StreamItem("name 3", "2016-05-17"));
        myOptions.add(new StreamItem("name 3", "2016-05-17"));
        myOptions.add(new StreamItem("name 3", "2016-05-17"));
        myOptions.add(new StreamItem("name 3", "2016-05-17"));
        myOptions.add(new StreamItem("name 2", "2016-06-05"));
        myOptions.add(new StreamItem("name 3", "2016-05-17"));*/

        HashMap<String, List<StreamItem>> groupedHashMap = groupDataIntoHashMap(myOptions);


        for (String date : groupedHashMap.keySet()) {
            HeaderItem dateItem = new HeaderItem();
            dateItem.setDate(date);
            consolidatedList.add(dateItem);


            for (StreamItem pojoOfJsonArray : groupedHashMap.get(date)) {
                EventItem generalItem = new EventItem();
                generalItem.setStreamItem(pojoOfJsonArray);//setBookingDataTabs(bookingDataTabs);
                consolidatedList.add(generalItem);
            }
        }

        adapter = new StreamArrayAdapter(this, consolidatedList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);

    }





    private HashMap<String, List<StreamItem>> groupDataIntoHashMap(List<StreamItem> listOfPojosOfJsonArray) {

        HashMap<String, List<StreamItem>> groupedHashMap = new HashMap<>();

        for (StreamItem pojoOfJsonArray : listOfPojosOfJsonArray) {

            String hashMapKey = pojoOfJsonArray.getDate();

            if (groupedHashMap.containsKey(hashMapKey)) {
                // The key is already in the HashMap; add the pojo object
                // against the existing key.
                groupedHashMap.get(hashMapKey).add(pojoOfJsonArray);
            } else {
                // The key is not there in the HashMap; create a new key-value pair
                List<StreamItem> list = new ArrayList<>();
                list.add(pojoOfJsonArray);
                groupedHashMap.put(hashMapKey, list);
            }
        }


        return groupedHashMap;
    }


        private void parseJSON() {
            final List<StreamItem> events = new ArrayList<>();

            String url = "https://netsync.unl.edu/feeds/apps/capitol_live/";


            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {


                    for (int i = 0; i < response.length(); i++) {

                        try {
                            JSONObject e = response.getJSONObject(i);
                            String date = e.getString("streamStart");


                            String des = e.getString("desc");

                            String image = e.getString("imgName");
                            String title = e.getString("category");


                            StreamItem str = new StreamItem(date, title, des, image);



                            myOptions.add(str);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    adapter.notifyDataSetChanged();


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Log.e("Volley", error.toString());


                }
            });

            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(jsonArrayRequest);




    }
}

enter code here

This is my data model POJO

public class StreamItem {

    public String date;
    public String title;
    public String desc;
    public String image;
    public String url;



 public StreamItem(String date , String title , String desc , String image , String url) {
        this.date = date;
        this.title = title;
        this.desc = desc;
        this.image = image;
        this.url = url;
    }



  public String getUrl(){
      return url;

    }

    public void setUrl(String url){
      this.url = url;
    }


    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }



    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }


}
  • try to set recycler adapter once you get the arraylist from the response.. – Mohit patel Jun 07 '19 at 06:03
  • I did that too, still it shows blank in the layout – dipalbhandari Jun 07 '19 at 06:13
  • Debug and check there is data in the arraylist you are passing to the recycler's adapter. – Mohit patel Jun 07 '19 at 06:15
  • What interesting I found in the debugging is when I print the arraylist inside the method it prints the data , but when I print it after calling the parseJSON method it doesn't print anything – dipalbhandari Jun 07 '19 at 06:20
  • When i print after this line parseJson() , it prints nothing – dipalbhandari Jun 07 '19 at 06:21
  • if there is data after this piece of code "myOptions.add(str);", Then you can set adapter to your recycler view after this by passing myOptions list to its constructor – Mohit patel Jun 07 '19 at 06:24
  • i did this mRecyclerView.setAdapter(adapter); still not working though – dipalbhandari Jun 07 '19 at 06:27
  • adapter = new StreamArrayAdapter(this, myOptions); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(adapter); Try this piece of code. – Mohit patel Jun 07 '19 at 06:28
  • But my StreamArrayAdapter doesn't take streamlist objects it is multiview types. You can look at the code I have tried to explain as much as possible. If that helps to answer this question. ListItem has two layouts in it one is header and other is event, whereas streamList class is my data model that has few parameters like date , title , description and this need to be be grouped by date – dipalbhandari Jun 07 '19 at 06:33
  • you are working really hard. Have you seen [Gson](https://github.com/google/gson)? I would also suggest that you start using [Retrofit](https://square.github.io/retrofit/). – Kostas Drak Jun 07 '19 at 06:47
  • I have tried both same result though – dipalbhandari Jun 08 '19 at 07:10

1 Answers1

0

You are getting data in an asynchronous way but you are setting data in recyclerview as a synchronous way that's why the list is empty. Follow the given strategy:

Replace adapter.notifyDataSetChanged() to update() method and remove all code after parseJSON(); method.

private void update(){ 

    HashMap<String, List<StreamItem>> groupedHashMap = groupDataIntoHashMap(myOptions);


            for (String date : groupedHashMap.keySet()) {
                HeaderItem dateItem = new HeaderItem();
                dateItem.setDate(date);
                consolidatedList.add(dateItem);


                for (StreamItem pojoOfJsonArray : groupedHashMap.get(date)) {
                    EventItem generalItem = new EventItem();
                    generalItem.setStreamItem(pojoOfJsonArray);//setBookingDataTabs(bookingDataTabs);
                    consolidatedList.add(generalItem);
                }
            }

            adapter = new StreamArrayAdapter(this, consolidatedList);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mRecyclerView.setLayoutManager(layoutManager);
            mRecyclerView.setAdapter(adapter);}
Sultan Mahmud
  • 1,245
  • 8
  • 18
  • Thank you so much. I really mean it. It worked. Thanks alot – dipalbhandari Jun 07 '19 at 06:57
  • What do you mean by I am adding dates in an asynchronous way? Can you tell more what was the mistake? I had the dates in decreasing order though. – dipalbhandari Jun 07 '19 at 06:58
  • Hey I did the way told , but I recently found that the events are not under specific dates. What I mean is say if there are two events for dates , they are displayed in different header there are two headers for the same date. But every events on the same date should go within that header – dipalbhandari Jun 07 '19 at 21:57
  • @dipalbhandari what do you mean by date? give an example here. You have a problem with your logic inside POJO I think. So add your pojo file – Sultan Mahmud Jun 08 '19 at 16:20
  • I have added by POJO file.What I mean by date is what I want to display in layout. If there are series of event occured in same date that should be under that same heading. Say there are two events in JSON file occuring in same date. That mean date should be the heading (for example June 5 , 2019) and the two events should be under it. I have also posted the pic there. I have added the other code too please refer it. Thanks for what you r doing – dipalbhandari Jun 09 '19 at 01:30
  • When I randomly create the StreamItem object ( you can see this in MainActivity where I have commented) it works fine. The events are arranged within the same date. But why is there problem when I am reading from JSON? It just return blank layout – dipalbhandari Jun 09 '19 at 02:48
  • As far as I remember when I saw the API that you attached the start time is different on the same date. And you are using it as a key and that's why the different header is showing. So mention the API url . – Sultan Mahmud Jun 09 '19 at 03:39
  • Can you tell me how to sort in ascending order? The way I am getting is in descending order. The items in the JSON are kept in descending order – dipalbhandari Jun 10 '19 at 14:48
  • What my question is, in most of the tutorial for onclick listener they use the reference of their data model and pass that on the adapter. But In my case, I am using ListItem as a reference while passing on the adapter. So, how much onclick listener works on this case? Thanks – dipalbhandari Jun 10 '19 at 18:18
  • @dipalbhandari you want to sort the data for the basis of which field? – Sultan Mahmud Jun 11 '19 at 04:32
  • I figured it out. Many thanks to you. How can we remove the row from recycler view automatically? Say if my stream ends at 5 pm. I want it to remove from 5:01 pm. How can I achieve this? Thanks – dipalbhandari Jun 11 '19 at 16:12
  • remove the item from list and reset the adapter data – Sultan Mahmud Jun 12 '19 at 03:42
  • Thank you. May I know how to play m3u8 format in android studio? The one I am using it just gives me the blank and after a few seconds says the video can't be playede ,Whenever the starttime in one of the recycler view items matches with the current time, I want to play a live stream vide when user click on it – dipalbhandari Jun 13 '19 at 01:14