Click here to Skip to main content
15,902,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have an ArrayList of ‘wholeYearRiskArray’, at each index of ArrayList there is another ArrayList of JSONObjects that contains the per month news/risks. Each index represents one month of news/risks.
I want to show the `displaydate` and `subject` properties of each JSONObject in the ListView.
Because each month data is separated by other month data by index.

I want to generate Fragments in ViewPager without any tabs. Each Fragment will hold each data of a month. The Fragments will dynamically generate according to the size of `wholeYearRisksArray`.

Here is the picture that shows the response.

http://i.imgur.com/3RvqDMn.png[^]

Here is the picture that i want to implement.

http://i.imgur.com/NQdkUXr.png[^]

Here is my java code.

Java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.android.geteventdataservice.R;
import com.example.android.geteventdataservice.models.Risks;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    public static String TAG = MainActivity.class.getSimpleName();
    ArrayList<Risks> risksArrayList = new ArrayList<>();
    HashMap<String, String> firstObjectHashMap = new HashMap<>();
    HashMap<String, String> lastObjectHashMap = new HashMap<>();
    String latestDateStr;
    String oldestDateStr;
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime formatedLatestDate;
    DateTime formatedOldestDate;
    DateTime upDate;

    JSONArray filteredJSONArray = new JSONArray();
    ArrayList<ArrayList<JSONObject>> wholeYearRiskArray = new ArrayList<>();
    Risks risks = new Risks();
    private String JsonUrl = "https://api.myjson.com/bins/4goeq";  // https://api.myjson.com/bins/4goeq
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest req = new StringRequest(JsonUrl,

                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");

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

                                JSONObject jsonObjectFromArray = jsonArray.getJSONObject(i);

                                if (jsonObjectFromArray.getString("publishtype").equals("PUBLISHED")) {

                                    filteredJSONArray.put(jsonObjectFromArray);

                                    risks.setUID(jsonObjectFromArray.getString("UID"));
                                    risks.setSubject(jsonObjectFromArray.getString("subject"));
                                    risks.setArticletext(jsonObjectFromArray.getString("articletext"));
                                    risks.setDisplaydate(jsonObjectFromArray.getString("displaydate"));
                                    risks.setPublishdate(jsonObjectFromArray.getString("publishdate"));
                                    risks.setKeywords(jsonObjectFromArray.getString("keywords"));
                                    risks.setPublishdate(jsonObjectFromArray.getString("publishtype"));
                                    risks.setTimestamp(jsonObjectFromArray.getString("timestamp"));

                                    risksArrayList.add(risks);
                                }
                            }
                            risksArrayList.get(0);

                            JSONObject firstObjectFromJsonArray = filteredJSONArray.getJSONObject(0);
                            JSONObject lastObjectFromJsonArray = filteredJSONArray.getJSONObject(filteredJSONArray.length() - 1);

                            firstObjectHashMap.put("UID", firstObjectFromJsonArray.getString("UID"));
                            firstObjectHashMap.put("subject", firstObjectFromJsonArray.getString("subject"));
                            firstObjectHashMap.put("articletext", firstObjectFromJsonArray.getString("articletext"));
                            firstObjectHashMap.put("displaydate", firstObjectFromJsonArray.getString("displaydate"));
                            firstObjectHashMap.put("publishdate", firstObjectFromJsonArray.getString("publishdate"));
                            firstObjectHashMap.put("keywords", firstObjectFromJsonArray.getString("keywords"));
                            firstObjectHashMap.put("publishtype", firstObjectFromJsonArray.getString("publishtype"));
                            firstObjectHashMap.put("timestamp", firstObjectFromJsonArray.getString("timestamp"));

                            lastObjectHashMap.put("UID", lastObjectFromJsonArray.getString("UID"));
                            lastObjectHashMap.put("subject", lastObjectFromJsonArray.getString("subject"));
                            lastObjectHashMap.put("articletext", lastObjectFromJsonArray.getString("articletext"));
                            lastObjectHashMap.put("displaydate", lastObjectFromJsonArray.getString("displaydate"));
                            lastObjectHashMap.put("publishdate", lastObjectFromJsonArray.getString("publishdate"));
                            lastObjectHashMap.put("keywords", lastObjectFromJsonArray.getString("keywords"));
                            lastObjectHashMap.put("publishtype", lastObjectFromJsonArray.getString("publishtype"));
                            lastObjectHashMap.put("timestamp", lastObjectFromJsonArray.getString("timestamp"));

                            oldestDateStr = firstObjectHashMap.get("publishdate");
                            latestDateStr = lastObjectHashMap.get("publishdate");

                            oldestDateStr = oldestDateStr.substring(0, 10);
                            oldestDateStr = oldestDateStr + " 00:00:00";

                            formatedOldestDate = fmt.parseDateTime(oldestDateStr);
                            formatedLatestDate = fmt.parseDateTime(latestDateStr);

                            int daysInMonth;

                            ArrayList<JSONObject> perMonthRisksArray = new ArrayList<JSONObject>();

                            while (formatedOldestDate.isBefore(formatedLatestDate) || formatedOldestDate.isEqual(formatedLatestDate)) {

                                daysInMonth = formatedOldestDate.dayOfMonth().getMaximumValue();
                                upDate = formatedOldestDate.plusDays(daysInMonth - 1);

                                long formatedLatestDateMillis = formatedOldestDate.getMillis();
                                long upDateMillis = upDate.getMillis();

                                perMonthRisksArray = fetchObjectsByDate(filteredJSONArray, formatedLatestDateMillis, upDateMillis);

                                wholeYearRiskArray.add(perMonthRisksArray);
                                formatedOldestDate = upDate.plusDays(1);

                            }
                            wholeYearRiskArray.get(0);
                            Log.d(TAG, Integer.toString(wholeYearRiskArray.size()));
                            risksArrayList.get(0);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();

            }
        }
        );
        queue.add(req);
    }

    public ArrayList<JSONObject> fetchObjectsByDate(JSONArray array, long startDate, long endDate) {
        final ArrayList<JSONObject> list = new ArrayList<>();

        for (int i = 0; i < array.length(); i++) {
            final JSONObject object = array.optJSONObject(i);
            if (object != null) {
                final String dateStr = object.optString("publishdate");
                if (dateStr != null) {

                    final long date = fmt.parseDateTime(dateStr).getMillis();
                    if ((date >= startDate) && (date <= endDate)) {
                        list.add(object);
                    }
                }
            }
        }
        return list;
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900