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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
|
package org.wordpress.android.ui.stats;
import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import org.wordpress.android.R;
import org.wordpress.android.ui.stats.models.GeoviewModel;
import org.wordpress.android.ui.stats.models.GeoviewsModel;
import org.wordpress.android.ui.stats.service.StatsService;
import org.wordpress.android.util.AppLog;
import org.wordpress.android.util.DisplayUtils;
import org.wordpress.android.util.FormatUtils;
import org.wordpress.android.util.GravatarUtils;
import org.wordpress.android.widgets.WPNetworkImageView;
import java.util.List;
public class StatsGeoviewsFragment extends StatsAbstractListFragment {
public static final String TAG = StatsGeoviewsFragment.class.getSimpleName();
private GeoviewsModel mCountries;
@Override
protected boolean hasDataAvailable() {
return mCountries != null;
}
@Override
protected void saveStatsData(Bundle outState) {
if (hasDataAvailable()) {
outState.putSerializable(ARG_REST_RESPONSE, mCountries);
}
}
@Override
protected void restoreStatsData(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(ARG_REST_RESPONSE)) {
mCountries = (GeoviewsModel) savedInstanceState.getSerializable(ARG_REST_RESPONSE);
}
}
@SuppressWarnings("unused")
public void onEventMainThread(StatsEvents.CountriesUpdated event) {
if (!shouldUpdateFragmentOnUpdateEvent(event)) {
return;
}
mCountries = event.mCountries;
updateUI();
}
@SuppressWarnings("unused")
public void onEventMainThread(StatsEvents.SectionUpdateError event) {
if (!shouldUpdateFragmentOnErrorEvent(event)) {
return;
}
mCountries = null;
showErrorUI(event.mError);
}
private void hideMap() {
if (!isAdded()) {
return;
}
mTopPagerContainer.setVisibility(View.GONE);
}
private void showMap(final List<GeoviewModel> countries) {
if (!isAdded()) {
return;
}
// setting up different margins for the map. We're basically remove left margins since the
// chart service produce a map that's slightly shifted on the right. See the Web version.
int dp4 = DisplayUtils.dpToPx(mTopPagerContainer.getContext(), 4);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, dp4, 0);
mTopPagerContainer.setLayoutParams(layoutParams);
mTopPagerContainer.removeAllViews();
// must wait for mTopPagerContainer to be fully laid out (ie: measured). Then we can read the width and
// calculate the right height for the map div
mTopPagerContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mTopPagerContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
if (!isAdded()) {
return;
}
StringBuilder dataToLoad = new StringBuilder();
for (int i = 0; i < countries.size(); i++) {
final GeoviewModel currentCountry = countries.get(i);
dataToLoad.append("['").append(currentCountry.getCountryFullName()).append("',")
.append(currentCountry.getViews()).append("],");
}
// This is the label that is shown when the user taps on a region
String label = getResources().getString(getTotalsLabelResId());
// See: https://developers.google.com/chart/interactive/docs/gallery/geochart
// Loading the v42 of the Google Charts API, since the latest stable version has a problem with the legend. https://github.com/wordpress-mobile/WordPress-Android/issues/4131
// https://developers.google.com/chart/interactive/docs/release_notes#release-candidate-details
String htmlPage = "<html>" +
"<head>" +
"<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>" +
"<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>" +
"<script type=\"text/javascript\">" +
"google.charts.load('42', {'packages':['geochart']});" +
"google.charts.setOnLoadCallback(drawRegionsMap);" +
"function drawRegionsMap() {" +
"var data = google.visualization.arrayToDataTable(" +
"[" +
"['Country', '" + label + "']," +
dataToLoad +
"]);" +
"var options = {keepAspectRatio: true, region: 'world', colorAxis: { colors: [ '#FFF088', '#F34605' ] }, enableRegionInteractivity: true};" +
"var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));" +
"chart.draw(data, options);" +
"}" +
"</script>" +
"</head>" +
"<body>" +
"<div id=\"regions_div\" style=\"width: 100%; height: 100%;\"></div>" +
"</body>" +
"</html>";
WebView webView = new WebView(getActivity());
mTopPagerContainer.addView(webView);
int width = mTopPagerContainer.getWidth();
int height = width * 3 / 4;
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) webView.getLayoutParams();
params.width = WebView.LayoutParams.MATCH_PARENT;
params.height = height;
webView.setLayoutParams(params);
webView.setWebViewClient(new MyWebViewClient()); // Hide map in case of unrecoverable errors
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.loadData(htmlPage, "text/html", "UTF-8");
}
});
mTopPagerContainer.setVisibility(View.VISIBLE);
}
// Hide the Map in case of errors
private class MyWebViewClient extends WebViewClient {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
mTopPagerContainer.setVisibility(View.GONE);
AppLog.e(AppLog.T.STATS, "Cannot load geochart."
+ " ErrorCode: " + errorCode
+ " Description: " + description
+ " Failing URL: " + failingUrl);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
mTopPagerContainer.setVisibility(View.GONE);
AppLog.e(AppLog.T.STATS, "Cannot load geochart. SSL ERROR. " + error.toString());
}
}
@Override
protected void updateUI() {
if (!isAdded()) {
return;
}
if (hasCountries()) {
List<GeoviewModel> countries = getCountries();
ArrayAdapter adapter = new GeoviewsAdapter(getActivity(), countries);
StatsUIHelper.reloadLinearLayout(getActivity(), adapter, mList, getMaxNumberOfItemsToShowInList());
showHideNoResultsUI(false);
showMap(countries);
} else {
showHideNoResultsUI(true);
hideMap();
}
}
private boolean hasCountries() {
return mCountries != null && mCountries.getCountries() != null;
}
private List<GeoviewModel> getCountries() {
if (!hasCountries()) {
return null;
}
return mCountries.getCountries();
}
@Override
protected boolean isViewAllOptionAvailable() {
return (hasCountries()
&& mCountries.getCountries().size() > MAX_NUM_OF_ITEMS_DISPLAYED_IN_LIST);
}
@Override
protected boolean isExpandableList() {
return false;
}
private class GeoviewsAdapter extends ArrayAdapter<GeoviewModel> {
private final List<GeoviewModel> list;
private final Activity context;
private final LayoutInflater inflater;
public GeoviewsAdapter(Activity context, List<GeoviewModel> list) {
super(context, R.layout.stats_list_cell, list);
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
rowView = inflater.inflate(R.layout.stats_list_cell, parent, false);
// configure view holder
StatsViewHolder viewHolder = new StatsViewHolder(rowView);
rowView.setTag(viewHolder);
}
final GeoviewModel currentRowData = list.get(position);
StatsViewHolder holder = (StatsViewHolder) rowView.getTag();
// fill data
String entry = currentRowData.getCountryFullName();
String imageUrl = currentRowData.getFlatFlagIconURL();
int total = currentRowData.getViews();
holder.setEntryText(entry);
holder.totalsTextView.setText(FormatUtils.formatDecimal(total));
// image (country flag)
holder.networkImageView.setImageUrl(
GravatarUtils.fixGravatarUrl(imageUrl, mResourceVars.headerAvatarSizePx),
WPNetworkImageView.ImageType.BLAVATAR);
holder.networkImageView.setVisibility(View.VISIBLE);
return rowView;
}
}
@Override
protected int getEntryLabelResId() {
return R.string.stats_entry_country;
}
@Override
protected int getTotalsLabelResId() {
return R.string.stats_totals_views;
}
@Override
protected int getEmptyLabelTitleResId() {
return R.string.stats_empty_geoviews;
}
@Override
protected int getEmptyLabelDescResId() {
return R.string.stats_empty_geoviews_desc;
}
@Override
protected StatsService.StatsEndpointsEnum[] sectionsToUpdate() {
return new StatsService.StatsEndpointsEnum[]{
StatsService.StatsEndpointsEnum.GEO_VIEWS
};
}
@Override
public String getTitle() {
return getString(R.string.stats_view_countries);
}
}
|