-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSONDataHandler.java
210 lines (176 loc) · 6.91 KB
/
JSONDataHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/**
* @author: Gean Maidana Dollanarte
* */
package com.example.fetch_exercise;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Class retrieves JSON data from a URL, eliminates instances where name is
* either null or blank, then sorts it according to
* listId, and when the listId is the same, it sorts by id.
* The data is displayed in a table with rows for each JSON data by calling
* the populateTable() method in the MainActivity class.
*
* */
public class JSONDataHandler implements Runnable
{
// This variable has setter and getter methods for it.
// It will be set at the end of the sortJSONData() method.
// It will retrieved in the populateTable() method (in the
// MainActivity class) when we have to dynamically create the rows for the
// table using the sorted JSON data.
private static JSONArray sortedJsonArray;
// Static variable for MainActivity, used in the constructor
// so that we have the same reference for the MainActivity class
// throughout the program running
private MainActivity mainActivity;
public JSONDataHandler(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
/**
* fetchJSONData(): This method opens the connection
* with the FETCH_URL and retrieves JSON data.
* @param: inputURL inputURL is used to open the URL connection
* and get the JSON data
* */
public void fetchJSONData(URL inputURL)
{
// This method is called in onCreate() in MainActivity and Android
// does not allow network operations in the UI thread so a new
// thread needs to be created
new Thread(()-> {
try
{
HttpURLConnection con = createHttpURLConnection(inputURL);
// Read response from server
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
// jsonArray holds all the JSON Data but it's not sorted
JSONArray jsonArray = new JSONArray(response.toString());
// sortJSONData() is not called in the onCreate() method
// because we don't want the threads in fetchJSONData() and
// sortJSONData() to run concurrently because that can cause
// data inconsistency problems, we want these two threads to
// run sequentially, so sortJSONData() is called at end of
// the current thread we are in
sortJSONData(jsonArray);
}
catch(Exception e)
{
Log.e("MyApp", "Exception", e);
}
}).start(); // End of thread
} // End of fetchJSONData()
/**
* sortJSONData(): This method takes an input JSONArray object and
* uses it sort the inputted JSON array.
* @param: jsonArray the jsonArray is the unsorted JSON Array that
* will be sorted in this method
* */
public void sortJSONData(JSONArray jsonArray) throws JSONException
{
new Thread(()-> {
try {
// This list will hold jsonList after we remove
// names that are null or blank for the jsonArray parameter
// Afterwards, jsonList will be sorted according to listId, and
// also by id in cases where listId are the same
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
if (!obj.isNull("name") &&
!obj.getString("name").isEmpty())
{
jsonList.add(obj);
}
}
// Sort the list by "listId" and "id" using a Comparator
Collections.sort(jsonList, new Comparator<JSONObject>()
{
@Override
public int compare(JSONObject o1, JSONObject o2)
{
int listId1 = o1.optInt("listId");
int listId2 = o2.optInt("listId");
if (listId1 == listId2)
{
String id1 = o1.optString("id", "");
String id2 = o2.optString("id", "");
int len1 = id1.length();
int len2 = id2.length();
if(len1 == len2)
{
return id1.compareTo(id2);
}
else
{
return Integer.compare(len1, len2);
}
}
return Integer.compare(listId1, listId2);
}
});
// Convert the sorted list back to a JSONArray
sortedJsonArray = new JSONArray(jsonList);
setSortedJsonArray(sortedJsonArray);
run();
}
catch(Exception e)
{
Log.e("MyApp", "Exception", e);
}
}).start(); // End of thread
} // End of sortJSONData()
public void setSortedJsonArray(JSONArray sortedJsonArray)
{
this.sortedJsonArray = sortedJsonArray;
}
public static JSONArray getSortedJsonArray()
{
return sortedJsonArray;
}
/**
* run() is a method defined in the Runnable interface
* This will call the populateTable() method in MainActivity
* */
@Override
public void run()
{
mainActivity.populateTable();
}
/**
* This method opens a URL connection with the given parameter
* @param: url used to URL to open the connection
* @return the url connection
* */
public HttpURLConnection createHttpURLConnection(URL url) throws IOException
{
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.connect();
return urlConnection;
}
}