Commit 790fc3bf2bb0bddf37ec9a0290bf194e8be08e34

Authored by Dinh Chu
1 parent 90cd21c2ba
Exists in master

update: fix bug count step

Showing 7 changed files with 200 additions and 25 deletions Inline Diff

app/src/main/java/com/dinhcv/lifelogpedometer/activity/HistoryContentFragment.java
1 package com.dinhcv.lifelogpedometer.activity; 1 package com.dinhcv.lifelogpedometer.activity;
2 2
3 import android.app.DatePickerDialog; 3 import android.app.DatePickerDialog;
4 import android.content.Context; 4 import android.content.Context;
5 import android.content.Intent; 5 import android.content.Intent;
6 import android.graphics.Color; 6 import android.graphics.Color;
7 import android.os.Bundle; 7 import android.os.Bundle;
8 import android.view.LayoutInflater; 8 import android.view.LayoutInflater;
9 import android.view.View; 9 import android.view.View;
10 import android.view.ViewGroup; 10 import android.view.ViewGroup;
11 import android.widget.Button; 11 import android.widget.Button;
12 import android.widget.DatePicker; 12 import android.widget.DatePicker;
13 import android.widget.ImageButton; 13 import android.widget.ImageButton;
14 import android.widget.ImageView; 14 import android.widget.ImageView;
15 import android.widget.LinearLayout; 15 import android.widget.LinearLayout;
16 import android.widget.TextView; 16 import android.widget.TextView;
17 17
18 import com.dinhcv.lifelogpedometer.R; 18 import com.dinhcv.lifelogpedometer.R;
19 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener; 19 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener;
20 import com.dinhcv.lifelogpedometer.model.structure.history.HistoryInfo; 20 import com.dinhcv.lifelogpedometer.model.structure.history.HistoryInfo;
21 import com.dinhcv.lifelogpedometer.portal.ApiServices; 21 import com.dinhcv.lifelogpedometer.portal.ApiServices;
22 import com.dinhcv.lifelogpedometer.portal.LLAPIManager; 22 import com.dinhcv.lifelogpedometer.portal.LLAPIManager;
23 import com.dinhcv.lifelogpedometer.utils.Const; 23 import com.dinhcv.lifelogpedometer.utils.Const;
24 import com.dinhcv.lifelogpedometer.utils.DayAxisValueFormatter; 24 import com.dinhcv.lifelogpedometer.utils.DayAxisValueFormatter;
25 import com.dinhcv.lifelogpedometer.utils.Debug; 25 import com.dinhcv.lifelogpedometer.utils.Debug;
26 import com.dinhcv.lifelogpedometer.utils.Utils; 26 import com.dinhcv.lifelogpedometer.utils.Utils;
27 import com.github.mikephil.charting.charts.BarChart; 27 import com.github.mikephil.charting.charts.BarChart;
28 import com.github.mikephil.charting.components.XAxis; 28 import com.github.mikephil.charting.components.XAxis;
29 import com.github.mikephil.charting.components.YAxis; 29 import com.github.mikephil.charting.components.YAxis;
30 import com.github.mikephil.charting.data.BarData; 30 import com.github.mikephil.charting.data.BarData;
31 import com.github.mikephil.charting.data.BarDataSet; 31 import com.github.mikephil.charting.data.BarDataSet;
32 import com.github.mikephil.charting.data.BarEntry; 32 import com.github.mikephil.charting.data.BarEntry;
33 import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; 33 import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
34 34
35 import org.json.JSONException; 35 import org.json.JSONException;
36 import org.json.JSONObject; 36 import org.json.JSONObject;
37 37
38 import java.util.ArrayList; 38 import java.util.ArrayList;
39 import java.util.Calendar; 39 import java.util.Calendar;
40 import java.util.Date; 40 import java.util.Date;
41 import java.util.List; 41 import java.util.List;
42 42
43 import butterknife.BindView; 43 import butterknife.BindView;
44 import butterknife.ButterKnife; 44 import butterknife.ButterKnife;
45 import butterknife.OnClick; 45 import butterknife.OnClick;
46 46
47 import static com.github.mikephil.charting.utils.ColorTemplate.rgb; 47 import static com.github.mikephil.charting.utils.ColorTemplate.rgb;
48 48
49 public class HistoryContentFragment extends FragmentBase { 49 public class HistoryContentFragment extends FragmentBase {
50 50
51 @BindView(R.id.btn_left_date) 51 @BindView(R.id.btn_left_date)
52 ImageButton btnLeftDate; 52 ImageButton btnLeftDate;
53 @BindView(R.id.btn_right_date) 53 @BindView(R.id.btn_right_date)
54 ImageButton btnRightDate; 54 ImageButton btnRightDate;
55 @BindView(R.id.tv_date) 55 @BindView(R.id.tv_date)
56 TextView tvDate; 56 TextView tvDate;
57 @BindView(R.id.tv_week_day) 57 @BindView(R.id.tv_week_day)
58 TextView tvWeekDay; 58 TextView tvWeekDay;
59 private ImageView btnFace; 59 private ImageView btnFace;
60 private ImageView btnTwitter; 60 private ImageView btnTwitter;
61 private ImageView btnLine; 61 private ImageView btnLine;
62 private ImageView btnEmail; 62 private ImageView btnEmail;
63 private ImageView btnOther; 63 private ImageView btnOther;
64 @BindView(R.id.tv_steps) 64 @BindView(R.id.tv_steps)
65 TextView tvStep; 65 TextView tvStep;
66 @BindView(R.id.tv_remainingStep) 66 @BindView(R.id.tv_remainingStep)
67 TextView tvRemain; 67 TextView tvRemain;
68 @BindView(R.id.tv_stepRateDone) 68 @BindView(R.id.tv_stepRateDone)
69 TextView tvRateDone; 69 TextView tvRateDone;
70 @BindView(R.id.tv_smallRemain) 70 @BindView(R.id.tv_smallRemain)
71 TextView tvSmallRemain; 71 TextView tvSmallRemain;
72 @BindView(R.id.tv_stepGoal) 72 @BindView(R.id.tv_stepGoal)
73 TextView tvGoal; 73 TextView tvGoal;
74 @BindView(R.id.tv_stepRemain)
75 TextView tv_stepRemain;
74 76
75 @BindView(R.id.tv_caloConsumned) 77 @BindView(R.id.tv_caloConsumned)
76 TextView tvCaloConsumned; 78 TextView tvCaloConsumned;
77 @BindView(R.id.tv_distance) 79 @BindView(R.id.tv_distance)
78 TextView tvDistance; 80 TextView tvDistance;
79 @BindView(R.id.tv_time) 81 @BindView(R.id.tv_time)
80 TextView tvTime; 82 TextView tvTime;
81 83
82 @BindView(R.id.ll_bike) 84 @BindView(R.id.ll_bike)
83 LinearLayout llBike; 85 LinearLayout llBike;
84 @BindView(R.id.ll_walking) 86 @BindView(R.id.ll_walking)
85 LinearLayout llWalking; 87 LinearLayout llWalking;
86 @BindView(R.id.ll_running) 88 @BindView(R.id.ll_running)
87 LinearLayout llRunning; 89 LinearLayout llRunning;
88 @BindView(R.id.btn_oneDay) 90 @BindView(R.id.btn_oneDay)
89 Button btnOneDay; 91 Button btnOneDay;
90 @BindView(R.id.btn_oneWeek) 92 @BindView(R.id.btn_oneWeek)
91 Button btnOneWeek; 93 Button btnOneWeek;
92 @BindView(R.id.btn_oneMonth) 94 @BindView(R.id.btn_oneMonth)
93 Button btnOneMonth; 95 Button btnOneMonth;
94 @BindView(R.id.btn_threeMonth) 96 @BindView(R.id.btn_threeMonth)
95 Button btnThreeMonth; 97 Button btnThreeMonth;
96 @BindView(R.id.btn_sixMonth) 98 @BindView(R.id.btn_sixMonth)
97 Button btnSixMonth; 99 Button btnSixMonth;
98 100
99 // bar chart 101 // bar chart
100 private BarChart mBarChart; 102 private BarChart mBarChart;
101 private List<String> dateList; 103 private List<String> dateList;
102 private String[] mParties; 104 private String[] mParties;
103 private Integer[] mStep; 105 private Integer[] mStep;
104 106
105 private Date mAnaDate; 107 private Date mAnaDate;
106 private Calendar mCalendar; 108 private Calendar mCalendar;
107 109
108 private int mAnaDay; 110 private int mAnaDay;
109 private int mAnaMonth; 111 private int mAnaMonth;
110 private int mAnaYear; 112 private int mAnaYear;
111 113
112 private HistoryInfo mDataModWalking = new HistoryInfo(); 114 private HistoryInfo mDataModWalking = new HistoryInfo();
113 private HistoryInfo mDataModRunning = new HistoryInfo(); 115 private HistoryInfo mDataModRunning = new HistoryInfo();
114 private HistoryInfo mDataModBike = new HistoryInfo(); 116 private HistoryInfo mDataModBike = new HistoryInfo();
115 private HistoryInfo mDataCurrent = new HistoryInfo(); 117 private HistoryInfo mDataCurrent = new HistoryInfo();
116 118
117 private Const.DATA_TYPE dataType; 119 private Const.DATA_TYPE dataType;
118 private Const.STEP_TYPE stepType; 120 private Const.STEP_TYPE stepType;
119 121
120 private Context mContext; 122 private Context mContext;
121 private View mRootView; 123 private View mRootView;
122 124
123 private HistoryFragment mHistoryFragment; 125 private HistoryFragment mHistoryFragment;
124 126
125 public void setRootFragment(HistoryFragment frag) { 127 public void setRootFragment(HistoryFragment frag) {
126 this.mHistoryFragment = frag; 128 this.mHistoryFragment = frag;
127 } 129 }
128 130
129 @Override 131 @Override
130 public View onCreateView(final LayoutInflater inflater, final ViewGroup container, 132 public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
131 final Bundle savedInstanceState) { 133 final Bundle savedInstanceState) {
132 mRootView = inflater.inflate(R.layout.fragment_history_content, null); 134 mRootView = inflater.inflate(R.layout.fragment_history_content, null);
133 ButterKnife.bind(this, mRootView); 135 ButterKnife.bind(this, mRootView);
134 mContext = getActivity(); 136 mContext = getActivity();
135 initView(mRootView); 137 initView(mRootView);
136 initData(); 138 initData();
137 139
138 return mRootView; 140 return mRootView;
139 } 141 }
140 142
141 143
142 private void initView(View view) { 144 private void initView(View view) {
143 btnFace = (ImageView) view.findViewById(R.id.btn_face); 145 btnFace = (ImageView) view.findViewById(R.id.btn_face);
144 btnTwitter = (ImageView) view.findViewById(R.id.btn_twitter); 146 btnTwitter = (ImageView) view.findViewById(R.id.btn_twitter);
145 btnLine = (ImageView) view.findViewById(R.id.btn_line); 147 btnLine = (ImageView) view.findViewById(R.id.btn_line);
146 btnEmail = (ImageView) view.findViewById(R.id.btn_email); 148 btnEmail = (ImageView) view.findViewById(R.id.btn_email);
147 btnOther = (ImageView) view.findViewById(R.id.btn_other); 149 btnOther = (ImageView) view.findViewById(R.id.btn_other);
148 150
149 mBarChart = (BarChart) view.findViewById(R.id.chart); 151 mBarChart = (BarChart) view.findViewById(R.id.chart);
150 } 152 }
151 153
152 154
153 /** 155 /**
154 * Show date picker dialog 156 * Show date picker dialog
155 */ 157 */
156 private void handleAnaDatePicker() { 158 private void handleAnaDatePicker() {
157 159
158 new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() { 160 new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
159 @Override 161 @Override
160 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 162 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
161 163
162 mCalendar = Calendar.getInstance(); 164 mCalendar = Calendar.getInstance();
163 mCalendar.set(year, monthOfYear, dayOfMonth); 165 mCalendar.set(year, monthOfYear, dayOfMonth);
164 mAnaYear = year; 166 mAnaYear = year;
165 mAnaMonth = monthOfYear; 167 mAnaMonth = monthOfYear;
166 mAnaDay = dayOfMonth; 168 mAnaDay = dayOfMonth;
167 Date date = mCalendar.getTime(); 169 Date date = mCalendar.getTime();
168 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 170 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
169 tvWeekDay.setText(Utils.getWeekdayFromDate(date)); 171 tvWeekDay.setText(Utils.getWeekdayFromDate(date));
170 mAnaDate = date; 172 mAnaDate = date;
171 getHistoryData(dataType, mAnaDate); 173 getHistoryData(dataType, mAnaDate);
172 } 174 }
173 }, mAnaYear, mAnaMonth, mAnaDay).show(); 175 }, mAnaYear, mAnaMonth, mAnaDay).show();
174 176
175 } 177 }
176 178
177 179
178 /** 180 /**
179 * init data for 181 * init data for
180 */ 182 */
181 private void initData() { 183 private void initData() {
182 mCalendar = Calendar.getInstance(); 184 mCalendar = Calendar.getInstance();
183 mCalendar.setTime(new Date()); 185 mCalendar.setTime(new Date());
184 mAnaDate = mCalendar.getTime(); 186 mAnaDate = mCalendar.getTime();
185 mAnaYear = mCalendar.get(Calendar.YEAR); 187 mAnaYear = mCalendar.get(Calendar.YEAR);
186 mAnaMonth = mCalendar.get(Calendar.MONTH); 188 mAnaMonth = mCalendar.get(Calendar.MONTH);
187 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH); 189 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH);
188 190
189 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate)); 191 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate));
190 tvWeekDay.setText(Utils.getWeekdayFromDate(mAnaDate)); 192 tvWeekDay.setText(Utils.getWeekdayFromDate(mAnaDate));
191 193
192 dataType = Const.DATA_TYPE.ONE_DAY; 194 dataType = Const.DATA_TYPE.ONE_DAY;
193 stepType = Const.STEP_TYPE.WALKING; 195 stepType = Const.STEP_TYPE.WALKING;
194 updateUiType(); 196 updateUiType();
195 updateUiStepType(false, true, false); 197 updateUiStepType(false, true, false);
196 198
197 getHistoryData(dataType, mAnaDate); 199 getHistoryData(dataType, mAnaDate);
198 } 200 }
199 201
200 private void updateUiType() { 202 private void updateUiType() {
201 if (dataType == Const.DATA_TYPE.ONE_DAY) { 203 if (dataType == Const.DATA_TYPE.ONE_DAY) {
202 setButtonSelected(true, false, false, false, false); 204 setButtonSelected(true, false, false, false, false);
203 } else if (dataType == Const.DATA_TYPE.ONE_WEEK) { 205 } else if (dataType == Const.DATA_TYPE.ONE_WEEK) {
204 setButtonSelected(false, true, false, false, false); 206 setButtonSelected(false, true, false, false, false);
205 } else if (dataType == Const.DATA_TYPE.ONE_MONTH) { 207 } else if (dataType == Const.DATA_TYPE.ONE_MONTH) {
206 setButtonSelected(false, false, true, false, false); 208 setButtonSelected(false, false, true, false, false);
207 } else if (dataType == Const.DATA_TYPE.THREE_MONTH){ 209 } else if (dataType == Const.DATA_TYPE.THREE_MONTH){
208 setButtonSelected(false, false, false, true, false); 210 setButtonSelected(false, false, false, true, false);
209 } else if (dataType == Const.DATA_TYPE.SIX_MONTH){ 211 } else if (dataType == Const.DATA_TYPE.SIX_MONTH){
210 setButtonSelected(false, false, false, false, true); 212 setButtonSelected(false, false, false, false, true);
211 } 213 }
212 } 214 }
213 215
214 private void setButtonSelected(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5 ) { 216 private void setButtonSelected(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5 ) {
215 btnOneDay.setSelected(b1); 217 btnOneDay.setSelected(b1);
216 btnOneWeek.setSelected(b2); 218 btnOneWeek.setSelected(b2);
217 btnOneMonth.setSelected(b3); 219 btnOneMonth.setSelected(b3);
218 btnThreeMonth.setSelected(b4); 220 btnThreeMonth.setSelected(b4);
219 btnSixMonth.setSelected(b5); 221 btnSixMonth.setSelected(b5);
220 } 222 }
221 223
222 private void updateUiStepType(boolean b1, boolean b2, boolean b3) { 224 private void updateUiStepType(boolean b1, boolean b2, boolean b3) {
223 llBike.setSelected(b1); 225 llBike.setSelected(b1);
224 llWalking.setSelected(b2); 226 llWalking.setSelected(b2);
225 llRunning.setSelected(b3); 227 llRunning.setSelected(b3);
226 } 228 }
227 229
228 private void getHistoryData(Const.DATA_TYPE dataType, Date toDate){ 230 private void getHistoryData(Const.DATA_TYPE dataType, Date toDate){
229 231
230 Date fromDate = Utils.getFromDate(mAnaDate, dataType); 232 Date fromDate = Utils.getFromDate(mAnaDate, dataType);
231 233
232 showDialog(mContext); 234 showDialog(mContext);
233 ApiServices.history(fromDate, toDate, new LLAPIManagerListener() { 235 ApiServices.history(fromDate, toDate, new LLAPIManagerListener() {
234 @Override 236 @Override
235 public void onError(Error error) { 237 public void onError(Error error) {
236 Debug.error("Get data history error"); 238 Debug.error("Get data history error");
237 hiddenDialog(); 239 hiddenDialog();
238 showDialogNotData(); 240 showDialogNotData();
239 } 241 }
240 242
241 @Override 243 @Override
242 public void onSuccess(String json) { 244 public void onSuccess(String json) {
243 Debug.error("Get data history success"); 245 Debug.error("Get data history success");
244 hiddenDialog(); 246 hiddenDialog();
245 loadDataDone(json); 247 loadDataDone(json);
246 } 248 }
247 249
248 @Override 250 @Override
249 public void onSuccess(JSONObject object) { 251 public void onSuccess(JSONObject object) {
250 Debug.error("Get data history success"); 252 Debug.error("Get data history success");
251 hiddenDialog(); 253 hiddenDialog();
252 } 254 }
253 }); 255 });
254 } 256 }
255 257
256 private void showDialogNotData(){ 258 private void showDialogNotData(){
257 showAlerDialog(mContext, getResources().getString(R.string.can_not_get_data)); 259 showAlerDialog(mContext, getResources().getString(R.string.can_not_get_data));
258 } 260 }
259 261
260 private void loadDataDone(String jsonString) { 262 private void loadDataDone(String jsonString) {
261 JSONObject jsonObject = null; 263 JSONObject jsonObject = null;
262 try { 264 try {
263 jsonObject = new JSONObject(jsonString); 265 jsonObject = new JSONObject(jsonString);
264 int status = jsonObject.optInt("status"); 266 int status = jsonObject.optInt("status");
265 if (status == 1) { 267 if (status == 1) {
266 JSONObject jsonObject1 = jsonObject.optJSONObject("result"); 268 JSONObject jsonObject1 = jsonObject.optJSONObject("result");
267 JSONObject jsonMod1 = jsonObject1.getJSONObject("mode_1"); 269 JSONObject jsonMod1 = jsonObject1.optJSONObject("mode_1");
268 JSONObject jsonMod2 = jsonObject1.getJSONObject("mode_2"); 270 JSONObject jsonMod2 = jsonObject1.optJSONObject("mode_2");
269 JSONObject jsonMod3 = jsonObject1.getJSONObject("mode_3"); 271 JSONObject jsonMod3 = jsonObject1.optJSONObject("mode_3");
270 addDataModWalking(jsonMod1); 272 if (jsonMod1 != null)addDataModWalking(jsonMod1);
271 addDataModRunning(jsonMod2); 273 if (jsonMod2 != null)addDataModRunning(jsonMod2);
272 addDataModBike(jsonMod3); 274 if (jsonMod3 != null)addDataModBike(jsonMod3);
273 275
274 } 276 }
275 } catch (JSONException e) { 277 } catch (JSONException e) {
276 e.printStackTrace(); 278 e.printStackTrace();
277 mDataModWalking = new HistoryInfo(); 279 mDataModWalking = new HistoryInfo();
278 mDataModRunning = new HistoryInfo();; 280 mDataModRunning = new HistoryInfo();;
279 mDataModBike = new HistoryInfo();; 281 mDataModBike = new HistoryInfo();;
280 } 282 }
281 283
282 if (stepType == Const.STEP_TYPE.WALKING){ 284 if (stepType == Const.STEP_TYPE.WALKING){
283 mDataCurrent = mDataModWalking; 285 mDataCurrent = mDataModWalking;
284 }else if (stepType == Const.STEP_TYPE.RUNNING){ 286 }else if (stepType == Const.STEP_TYPE.RUNNING){
285 mDataCurrent = mDataModRunning; 287 mDataCurrent = mDataModRunning;
286 }else { 288 }else {
287 mDataCurrent = mDataModBike; 289 mDataCurrent = mDataModBike;
288 } 290 }
289 291
290 updateUI(); 292 updateUI();
291 } 293 }
292 294
293 private void updateUI(){ 295 private void updateUI(){
294 // get data server 296 // get data server
295 tvGoal.setText(getResources().getString(R.string.step_unit, mDataCurrent.getTaget())); 297 tvGoal.setText(getResources().getString(R.string.step_unit, mDataCurrent.getTaget()));
296 tvStep.setText(getResources().getString(R.string.step_unit, mDataCurrent.getSteps())); 298 tvStep.setText(getResources().getString(R.string.step_unit, mDataCurrent.getSteps()));
297 tvSmallRemain.setText(getResources().getString(R.string.step_unit_1, mDataCurrent.getStepRemain())); 299 tvSmallRemain.setText(getResources().getString(R.string.step_unit_1, mDataCurrent.getStepRemain()));
300 tv_stepRemain.setText(mDataCurrent.getStepRemain() + getResources().getString(R.string.step));
298 tvRemain.setText(getResources().getString(R.string.step_unit, mDataCurrent.getStepRemain())); 301 tvRemain.setText(getResources().getString(R.string.step_unit, mDataCurrent.getStepRemain()));
299 tvRateDone.setText(getResources().getString(R.string.percent_unit, Utils.convert2String2Decimal(mDataCurrent.getCompletePercent()))); 302 tvRateDone.setText(getResources().getString(R.string.percent_unit, Utils.convert2String2Decimal(mDataCurrent.getCompletePercent())));
300 tvCaloConsumned.setText(getResources().getString(R.string.kcal_unit, Utils.convert2String2Decimal(mDataCurrent.getKcal()))); 303 tvCaloConsumned.setText(getResources().getString(R.string.kcal_unit, Utils.convert2String2Decimal(mDataCurrent.getKcal())));
301 tvDistance.setText(getResources().getString(R.string.distance_unit, Utils.convert2String2Decimal(mDataCurrent.getDistance()))); 304 tvDistance.setText(getResources().getString(R.string.distance_unit, Utils.convert2String2Decimal(mDataCurrent.getDistance())));
302 tvTime.setText(getResources().getString(R.string.time_unit, Utils.convertTimeStringFromString(mDataCurrent.getTime()))); 305 tvTime.setText(getResources().getString(R.string.time_unit, Utils.convertTimeStringFromString(mDataCurrent.getTime())));
303 306
304 // update bar 307 // update bar
305 if (mDataCurrent.getDataChart() != null && mDataCurrent.getDataChart().size() == 24) { 308 if (mDataCurrent.getDataChart() != null && mDataCurrent.getDataChart().size() == 24) {
306 updateBars(); 309 updateBars();
307 } 310 }
308 311
309 } 312 }
310 313
311 private void updateBars() { 314 private void updateBars() {
312 dateList = new ArrayList<>(); 315 dateList = new ArrayList<>();
313 List<Integer> stepList = new ArrayList<>(); 316 List<Integer> stepList = new ArrayList<>();
314 317
315 stepList = mDataCurrent.getDataChart(); 318 stepList = mDataCurrent.getDataChart();
316 for (int i = 0; i < 24; i++){ 319 for (int i = 0; i < 24; i++){
317 dateList.add(String.valueOf(i)); 320 dateList.add(String.valueOf(i));
318 } 321 }
319 322
320 mStep = stepList.toArray(new Integer[0]); 323 mStep = stepList.toArray(new Integer[0]);
321 mParties = dateList.toArray(new String[0]); 324 mParties = dateList.toArray(new String[0]);
322 325
323 initGraph(); 326 initGraph();
324 } 327 }
325 328
326 private void initGraph(){ 329 private void initGraph(){
327 330
328 mBarChart.setDrawBarShadow(false); 331 mBarChart.setDrawBarShadow(false);
329 mBarChart.setDrawValueAboveBar(true); 332 mBarChart.setDrawValueAboveBar(true);
330 333
331 // if more than 60 entries are displayed in the chart, no values will be 334 // if more than 60 entries are displayed in the chart, no values will be
332 // drawn 335 // drawn
333 mBarChart.setMaxVisibleValueCount(60); 336 mBarChart.setMaxVisibleValueCount(60);
334 337
335 mBarChart.getDescription().setEnabled(false); 338 mBarChart.getDescription().setEnabled(false);
336 // scaling can now only be done on x- and y-axis separately 339 // scaling can now only be done on x- and y-axis separately
337 mBarChart.setPinchZoom(false); 340 mBarChart.setPinchZoom(false);
338 341
339 mBarChart.setDrawGridBackground(false); 342 mBarChart.setDrawGridBackground(false);
340 // mChart.setDrawYLabels(false); 343 // mChart.setDrawYLabels(false);
341 344
342 DayAxisValueFormatter xValueFormatter = new DayAxisValueFormatter(dateList); 345 DayAxisValueFormatter xValueFormatter = new DayAxisValueFormatter(dateList);
343 346
344 XAxis xAxis = mBarChart.getXAxis(); 347 XAxis xAxis = mBarChart.getXAxis();
345 xAxis.setLabelRotationAngle(0); 348 xAxis.setLabelRotationAngle(0);
346 xAxis.setPosition(XAxis.XAxisPosition.TOP); 349 xAxis.setPosition(XAxis.XAxisPosition.TOP);
347 xAxis.setDrawGridLines(true); 350 xAxis.setDrawGridLines(true);
348 xAxis.setLabelCount(10); 351 xAxis.setLabelCount(10);
349 xAxis.setTextColor(Color.WHITE); 352 xAxis.setTextColor(Color.WHITE);
350 xAxis.setValueFormatter(xValueFormatter); 353 xAxis.setValueFormatter(xValueFormatter);
351 354
352 355
353 YAxis leftAxis = mBarChart.getAxisLeft(); 356 YAxis leftAxis = mBarChart.getAxisLeft();
354 leftAxis.setDrawLabels(false); 357 leftAxis.setDrawLabels(false);
355 leftAxis.setDrawGridLines(false); 358 leftAxis.setDrawGridLines(false);
356 leftAxis.setAxisMinimum(0f); 359 leftAxis.setAxisMinimum(0f);
357 leftAxis.setAxisMaximum(10000f); 360 leftAxis.setAxisMaximum(10000f);
358 leftAxis.setDrawZeroLine(false); 361 leftAxis.setDrawZeroLine(false);
359 362
360 leftAxis.setEnabled(false); 363 leftAxis.setEnabled(false);
361 mBarChart.setDrawValueAboveBar(false); 364 mBarChart.setDrawValueAboveBar(false);
362 mBarChart.getAxisRight().setEnabled(false); 365 mBarChart.getAxisRight().setEnabled(false);
363 366
364 // set auto scale min max 367 // set auto scale min max
365 mBarChart.setAutoScaleMinMaxEnabled(true); 368 mBarChart.setAutoScaleMinMaxEnabled(true);
366 mBarChart.notifyDataSetChanged(); 369 mBarChart.notifyDataSetChanged();
367 370
368 // Set enimate y 371 // Set enimate y
369 mBarChart.animateY(2000); 372 mBarChart.animateY(2000);
370 373
371 setData(); 374 setData();
372 375
373 mBarChart.getLegend().setEnabled(false); 376 mBarChart.getLegend().setEnabled(false);
374 } 377 }
375 378
376 379
377 private void setData() { 380 private void setData() {
378 381
379 ArrayList<String> xVals = new ArrayList<>(); 382 ArrayList<String> xVals = new ArrayList<>();
380 for (int i = 0; i < mStep.length; i++) { 383 for (int i = 0; i < mStep.length; i++) {
381 xVals.add(mParties[i % mStep.length]); 384 xVals.add(mParties[i % mStep.length]);
382 } 385 }
383 386
384 ArrayList<BarEntry> yVals1 = new ArrayList<>(); 387 ArrayList<BarEntry> yVals1 = new ArrayList<>();
385 for (int i = 0; i < mStep.length; i++) { 388 for (int i = 0; i < mStep.length; i++) {
386 float val = (float) (mStep[i]*1); 389 float val = (float) (mStep[i]*1);
387 yVals1.add(new BarEntry(i, val)); 390 yVals1.add(new BarEntry(i, val));
388 } 391 }
389 392
390 BarDataSet set1; 393 BarDataSet set1;
391 394
392 if (mBarChart.getData() != null && mBarChart.getData().getDataSetCount() > 0) { 395 if (mBarChart.getData() != null && mBarChart.getData().getDataSetCount() > 0) {
393 set1 = (BarDataSet)mBarChart.getData().getDataSetByIndex(0); 396 set1 = (BarDataSet)mBarChart.getData().getDataSetByIndex(0);
394 set1.setValues(yVals1); 397 set1.setValues(yVals1);
395 mBarChart.getData().notifyDataChanged(); 398 mBarChart.getData().notifyDataChanged();
396 mBarChart.notifyDataSetChanged(); 399 mBarChart.notifyDataSetChanged();
397 } else { 400 } else {
398 ArrayList<Integer> colors = new ArrayList<>(); 401 ArrayList<Integer> colors = new ArrayList<>();
399 402
400 403
401 int[] MATERIAL_COLORS = {rgb("#40CDEF")}; 404 int[] MATERIAL_COLORS = {rgb("#40CDEF")};
402 405
403 for (int c : MATERIAL_COLORS) 406 for (int c : MATERIAL_COLORS)
404 colors.add(c); 407 colors.add(c);
405 408
406 set1 = new BarDataSet(yVals1, null); 409 set1 = new BarDataSet(yVals1, null);
407 410
408 set1.setColors(colors); 411 set1.setColors(colors);
409 412
410 ArrayList<IBarDataSet> dataSets = new ArrayList<>(); 413 ArrayList<IBarDataSet> dataSets = new ArrayList<>();
411 dataSets.add(set1); 414 dataSets.add(set1);
412 415
413 BarData data = new BarData(dataSets); 416 BarData data = new BarData(dataSets);
414 data.setValueTextSize(10f); 417 data.setValueTextSize(10f);
415 418
416 mBarChart.setData(data); 419 mBarChart.setData(data);
417 } 420 }
418 } 421 }
419 422
420 private void addDataModWalking(JSONObject jsonObject){ 423 private void addDataModWalking(JSONObject jsonObject){
421 if (jsonObject == null) return; 424 if (jsonObject == null) return;
422 mDataModWalking.setTaget(jsonObject.optInt("target")); 425 mDataModWalking.setTaget(jsonObject.optInt("target"));
423 mDataModWalking.setSteps(jsonObject.optInt("steps")); 426 mDataModWalking.setSteps(jsonObject.optInt("steps"));
424 mDataModWalking.setStepRemain(jsonObject.optInt("step_remain")); 427 mDataModWalking.setStepRemain(jsonObject.optInt("step_remain"));
425 mDataModWalking.setCompletePercent(jsonObject.optDouble("complete_percent")); 428 mDataModWalking.setCompletePercent(jsonObject.optDouble("complete_percent"));
426 mDataModWalking.setTime(jsonObject.optInt("time")); 429 mDataModWalking.setTime(jsonObject.optInt("time"));
427 mDataModWalking.setDistance(jsonObject.optInt("distance")); 430 mDataModWalking.setDistance(jsonObject.optInt("distance"));
428 mDataModWalking.setKcal(jsonObject.optInt("kcal")); 431 mDataModWalking.setKcal(jsonObject.optInt("kcal"));
429 432
430 JSONObject dataChart = jsonObject.optJSONObject("data_chart"); 433 JSONObject dataChart = jsonObject.optJSONObject("data_chart");
431 ArrayList<Integer> dataChartList = new ArrayList<>(); 434 ArrayList<Integer> dataChartList = new ArrayList<>();
432 dataChartList.add(dataChart.optInt("0")); 435 dataChartList.add(dataChart.optInt("0"));
433 dataChartList.add(dataChart.optInt("1")); 436 dataChartList.add(dataChart.optInt("1"));
434 dataChartList.add(dataChart.optInt("2")); 437 dataChartList.add(dataChart.optInt("2"));
435 dataChartList.add(dataChart.optInt("3")); 438 dataChartList.add(dataChart.optInt("3"));
436 dataChartList.add(dataChart.optInt("4")); 439 dataChartList.add(dataChart.optInt("4"));
437 dataChartList.add(dataChart.optInt("5")); 440 dataChartList.add(dataChart.optInt("5"));
438 dataChartList.add(dataChart.optInt("6")); 441 dataChartList.add(dataChart.optInt("6"));
439 dataChartList.add(dataChart.optInt("7")); 442 dataChartList.add(dataChart.optInt("7"));
440 dataChartList.add(dataChart.optInt("8")); 443 dataChartList.add(dataChart.optInt("8"));
441 dataChartList.add(dataChart.optInt("9")); 444 dataChartList.add(dataChart.optInt("9"));
442 dataChartList.add(dataChart.optInt("10")); 445 dataChartList.add(dataChart.optInt("10"));
443 dataChartList.add(dataChart.optInt("11")); 446 dataChartList.add(dataChart.optInt("11"));
444 dataChartList.add(dataChart.optInt("12")); 447 dataChartList.add(dataChart.optInt("12"));
445 dataChartList.add(dataChart.optInt("13")); 448 dataChartList.add(dataChart.optInt("13"));
446 dataChartList.add(dataChart.optInt("14")); 449 dataChartList.add(dataChart.optInt("14"));
447 dataChartList.add(dataChart.optInt("15")); 450 dataChartList.add(dataChart.optInt("15"));
448 dataChartList.add(dataChart.optInt("16")); 451 dataChartList.add(dataChart.optInt("16"));
449 dataChartList.add(dataChart.optInt("17")); 452 dataChartList.add(dataChart.optInt("17"));
450 dataChartList.add(dataChart.optInt("18")); 453 dataChartList.add(dataChart.optInt("18"));
451 dataChartList.add(dataChart.optInt("19")); 454 dataChartList.add(dataChart.optInt("19"));
452 dataChartList.add(dataChart.optInt("20")); 455 dataChartList.add(dataChart.optInt("20"));
453 dataChartList.add(dataChart.optInt("21")); 456 dataChartList.add(dataChart.optInt("21"));
454 dataChartList.add(dataChart.optInt("22")); 457 dataChartList.add(dataChart.optInt("22"));
455 dataChartList.add(dataChart.optInt("23")); 458 dataChartList.add(dataChart.optInt("23"));
456 459
457 mDataModWalking.setDataChart(dataChartList); 460 mDataModWalking.setDataChart(dataChartList);
458 } 461 }
459 462
460 private void addDataModRunning(JSONObject jsonObject){ 463 private void addDataModRunning(JSONObject jsonObject){
461 if (jsonObject == null) return; 464 if (jsonObject == null) return;
462 mDataModRunning.setTaget(jsonObject.optInt("target")); 465 mDataModRunning.setTaget(jsonObject.optInt("target"));
463 mDataModRunning.setSteps(jsonObject.optInt("steps")); 466 mDataModRunning.setSteps(jsonObject.optInt("steps"));
464 mDataModRunning.setStepRemain(jsonObject.optInt("step_remain")); 467 mDataModRunning.setStepRemain(jsonObject.optInt("step_remain"));
465 mDataModRunning.setCompletePercent(jsonObject.optDouble("complete_percent")); 468 mDataModRunning.setCompletePercent(jsonObject.optDouble("complete_percent"));
466 mDataModRunning.setTime(jsonObject.optInt("time")); 469 mDataModRunning.setTime(jsonObject.optInt("time"));
467 mDataModRunning.setDistance(jsonObject.optInt("distance")); 470 mDataModRunning.setDistance(jsonObject.optInt("distance"));
468 mDataModRunning.setKcal(jsonObject.optInt("kcal")); 471 mDataModRunning.setKcal(jsonObject.optInt("kcal"));
469 472
470 JSONObject dataChart = jsonObject.optJSONObject("data_chart"); 473 JSONObject dataChart = jsonObject.optJSONObject("data_chart");
471 ArrayList<Integer> dataChartList = new ArrayList<>(); 474 ArrayList<Integer> dataChartList = new ArrayList<>();
472 dataChartList.add(dataChart.optInt("0")); 475 dataChartList.add(dataChart.optInt("0"));
473 dataChartList.add(dataChart.optInt("1")); 476 dataChartList.add(dataChart.optInt("1"));
474 dataChartList.add(dataChart.optInt("2")); 477 dataChartList.add(dataChart.optInt("2"));
475 dataChartList.add(dataChart.optInt("3")); 478 dataChartList.add(dataChart.optInt("3"));
476 dataChartList.add(dataChart.optInt("4")); 479 dataChartList.add(dataChart.optInt("4"));
477 dataChartList.add(dataChart.optInt("5")); 480 dataChartList.add(dataChart.optInt("5"));
478 dataChartList.add(dataChart.optInt("6")); 481 dataChartList.add(dataChart.optInt("6"));
479 dataChartList.add(dataChart.optInt("7")); 482 dataChartList.add(dataChart.optInt("7"));
480 dataChartList.add(dataChart.optInt("8")); 483 dataChartList.add(dataChart.optInt("8"));
481 dataChartList.add(dataChart.optInt("9")); 484 dataChartList.add(dataChart.optInt("9"));
482 dataChartList.add(dataChart.optInt("10")); 485 dataChartList.add(dataChart.optInt("10"));
483 dataChartList.add(dataChart.optInt("11")); 486 dataChartList.add(dataChart.optInt("11"));
484 dataChartList.add(dataChart.optInt("12")); 487 dataChartList.add(dataChart.optInt("12"));
485 dataChartList.add(dataChart.optInt("13")); 488 dataChartList.add(dataChart.optInt("13"));
486 dataChartList.add(dataChart.optInt("14")); 489 dataChartList.add(dataChart.optInt("14"));
487 dataChartList.add(dataChart.optInt("15")); 490 dataChartList.add(dataChart.optInt("15"));
488 dataChartList.add(dataChart.optInt("16")); 491 dataChartList.add(dataChart.optInt("16"));
489 dataChartList.add(dataChart.optInt("17")); 492 dataChartList.add(dataChart.optInt("17"));
490 dataChartList.add(dataChart.optInt("18")); 493 dataChartList.add(dataChart.optInt("18"));
491 dataChartList.add(dataChart.optInt("19")); 494 dataChartList.add(dataChart.optInt("19"));
492 dataChartList.add(dataChart.optInt("20")); 495 dataChartList.add(dataChart.optInt("20"));
493 dataChartList.add(dataChart.optInt("21")); 496 dataChartList.add(dataChart.optInt("21"));
494 dataChartList.add(dataChart.optInt("22")); 497 dataChartList.add(dataChart.optInt("22"));
495 dataChartList.add(dataChart.optInt("23")); 498 dataChartList.add(dataChart.optInt("23"));
496 499
497 mDataModRunning.setDataChart(dataChartList); 500 mDataModRunning.setDataChart(dataChartList);
498 } 501 }
499 502
500 private void addDataModBike(JSONObject jsonObject){ 503 private void addDataModBike(JSONObject jsonObject){
501 if (jsonObject == null) return; 504 if (jsonObject == null) return;
502 mDataModBike.setTaget(jsonObject.optInt("target")); 505 mDataModBike.setTaget(jsonObject.optInt("target"));
503 mDataModBike.setSteps(jsonObject.optInt("steps")); 506 mDataModBike.setSteps(jsonObject.optInt("steps"));
504 mDataModBike.setStepRemain(jsonObject.optInt("step_remain")); 507 mDataModBike.setStepRemain(jsonObject.optInt("step_remain"));
505 mDataModBike.setCompletePercent(jsonObject.optDouble("complete_percent")); 508 mDataModBike.setCompletePercent(jsonObject.optDouble("complete_percent"));
506 mDataModBike.setTime(jsonObject.optInt("time")); 509 mDataModBike.setTime(jsonObject.optInt("time"));
507 mDataModBike.setDistance(jsonObject.optInt("distance")); 510 mDataModBike.setDistance(jsonObject.optInt("distance"));
508 mDataModBike.setKcal(jsonObject.optInt("kcal")); 511 mDataModBike.setKcal(jsonObject.optInt("kcal"));
509 512
510 JSONObject dataChart = jsonObject.optJSONObject("data_chart"); 513 JSONObject dataChart = jsonObject.optJSONObject("data_chart");
511 ArrayList<Integer> dataChartList = new ArrayList<>(); 514 ArrayList<Integer> dataChartList = new ArrayList<>();
512 dataChartList.add(dataChart.optInt("0")); 515 dataChartList.add(dataChart.optInt("0"));
513 dataChartList.add(dataChart.optInt("1")); 516 dataChartList.add(dataChart.optInt("1"));
514 dataChartList.add(dataChart.optInt("2")); 517 dataChartList.add(dataChart.optInt("2"));
515 dataChartList.add(dataChart.optInt("3")); 518 dataChartList.add(dataChart.optInt("3"));
516 dataChartList.add(dataChart.optInt("4")); 519 dataChartList.add(dataChart.optInt("4"));
517 dataChartList.add(dataChart.optInt("5")); 520 dataChartList.add(dataChart.optInt("5"));
518 dataChartList.add(dataChart.optInt("6")); 521 dataChartList.add(dataChart.optInt("6"));
519 dataChartList.add(dataChart.optInt("7")); 522 dataChartList.add(dataChart.optInt("7"));
520 dataChartList.add(dataChart.optInt("8")); 523 dataChartList.add(dataChart.optInt("8"));
521 dataChartList.add(dataChart.optInt("9")); 524 dataChartList.add(dataChart.optInt("9"));
522 dataChartList.add(dataChart.optInt("10")); 525 dataChartList.add(dataChart.optInt("10"));
523 dataChartList.add(dataChart.optInt("11")); 526 dataChartList.add(dataChart.optInt("11"));
524 dataChartList.add(dataChart.optInt("12")); 527 dataChartList.add(dataChart.optInt("12"));
525 dataChartList.add(dataChart.optInt("13")); 528 dataChartList.add(dataChart.optInt("13"));
526 dataChartList.add(dataChart.optInt("14")); 529 dataChartList.add(dataChart.optInt("14"));
527 dataChartList.add(dataChart.optInt("15")); 530 dataChartList.add(dataChart.optInt("15"));
528 dataChartList.add(dataChart.optInt("16")); 531 dataChartList.add(dataChart.optInt("16"));
529 dataChartList.add(dataChart.optInt("17")); 532 dataChartList.add(dataChart.optInt("17"));
530 dataChartList.add(dataChart.optInt("18")); 533 dataChartList.add(dataChart.optInt("18"));
531 dataChartList.add(dataChart.optInt("19")); 534 dataChartList.add(dataChart.optInt("19"));
532 dataChartList.add(dataChart.optInt("20")); 535 dataChartList.add(dataChart.optInt("20"));
533 dataChartList.add(dataChart.optInt("21")); 536 dataChartList.add(dataChart.optInt("21"));
534 dataChartList.add(dataChart.optInt("22")); 537 dataChartList.add(dataChart.optInt("22"));
535 dataChartList.add(dataChart.optInt("23")); 538 dataChartList.add(dataChart.optInt("23"));
536 539
537 mDataModBike.setDataChart(dataChartList); 540 mDataModBike.setDataChart(dataChartList);
538 } 541 }
539 542
540 @OnClick({R.id.btn_oneDay, R.id.btn_oneWeek, R.id.btn_oneMonth, R.id.btn_threeMonth, 543 @OnClick({R.id.btn_oneDay, R.id.btn_oneWeek, R.id.btn_oneMonth, R.id.btn_threeMonth,
541 R.id.btn_sixMonth, R.id.btn_left_date, R.id.btn_right_date, R.id.ll_bike, 544 R.id.btn_sixMonth, R.id.btn_left_date, R.id.btn_right_date, R.id.ll_bike,
542 R.id.ll_walking, R.id.ll_running, R.id.rl_stepView}) 545 R.id.ll_walking, R.id.ll_running, R.id.rl_stepView})
543 public void onClick(View v){ 546 public void onClick(View v){
544 switch (v.getId()){ 547 switch (v.getId()){
545 case R.id.btn_left_date: 548 case R.id.btn_left_date:
546 mCalendar = Calendar.getInstance(); 549 mCalendar = Calendar.getInstance();
547 mCalendar.setTime(mAnaDate); 550 mCalendar.setTime(mAnaDate);
548 mCalendar.add(Calendar.DAY_OF_MONTH, -1); 551 mCalendar.add(Calendar.DAY_OF_MONTH, -1);
549 Date date = mCalendar.getTime(); 552 Date date = mCalendar.getTime();
550 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 553 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
551 tvWeekDay.setText(Utils.getWeekdayFromDate(date)); 554 tvWeekDay.setText(Utils.getWeekdayFromDate(date));
552 mAnaDate = date; 555 mAnaDate = date;
553 getHistoryData(dataType, mAnaDate); 556 getHistoryData(dataType, mAnaDate);
554 break; 557 break;
555 558
556 case R.id.btn_right_date: 559 case R.id.btn_right_date:
557 mCalendar = Calendar.getInstance(); 560 mCalendar = Calendar.getInstance();
558 mCalendar.setTime(mAnaDate); 561 mCalendar.setTime(mAnaDate);
559 mCalendar.add(Calendar.DAY_OF_MONTH, +1); 562 mCalendar.add(Calendar.DAY_OF_MONTH, +1);
560 Date date1 = mCalendar.getTime(); 563 Date date1 = mCalendar.getTime();
561 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date1)); 564 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date1));
562 tvWeekDay.setText(Utils.getWeekdayFromDate(date1)); 565 tvWeekDay.setText(Utils.getWeekdayFromDate(date1));
563 mAnaDate = date1; 566 mAnaDate = date1;
564 getHistoryData(dataType, mAnaDate); 567 getHistoryData(dataType, mAnaDate);
565 break; 568 break;
566 569
567 case R.id.btn_oneDay: 570 case R.id.btn_oneDay:
568 dataType = Const.DATA_TYPE.ONE_DAY; 571 dataType = Const.DATA_TYPE.ONE_DAY;
569 updateUiType(); 572 updateUiType();
570 getHistoryData(dataType, mAnaDate); 573 getHistoryData(dataType, mAnaDate);
571 break; 574 break;
572 575
573 case R.id.btn_oneWeek: 576 case R.id.btn_oneWeek:
574 dataType = Const.DATA_TYPE.ONE_WEEK; 577 dataType = Const.DATA_TYPE.ONE_WEEK;
575 updateUiType(); 578 updateUiType();
576 getHistoryData(dataType, mAnaDate); 579 getHistoryData(dataType, mAnaDate);
577 break; 580 break;
578 581
579 case R.id.btn_oneMonth: 582 case R.id.btn_oneMonth:
580 dataType = Const.DATA_TYPE.ONE_MONTH; 583 dataType = Const.DATA_TYPE.ONE_MONTH;
581 updateUiType(); 584 updateUiType();
582 getHistoryData(dataType, mAnaDate); 585 getHistoryData(dataType, mAnaDate);
583 break; 586 break;
584 587
585 case R.id.btn_threeMonth: 588 case R.id.btn_threeMonth:
586 dataType = Const.DATA_TYPE.THREE_MONTH; 589 dataType = Const.DATA_TYPE.THREE_MONTH;
587 updateUiType(); 590 updateUiType();
588 getHistoryData(dataType, mAnaDate); 591 getHistoryData(dataType, mAnaDate);
589 break; 592 break;
590 593
591 case R.id.btn_sixMonth: 594 case R.id.btn_sixMonth:
592 dataType = Const.DATA_TYPE.SIX_MONTH; 595 dataType = Const.DATA_TYPE.SIX_MONTH;
593 updateUiType(); 596 updateUiType();
594 getHistoryData(dataType, mAnaDate); 597 getHistoryData(dataType, mAnaDate);
595 break; 598 break;
596 599
597 case R.id.tv_date: 600 case R.id.tv_date:
598 handleAnaDatePicker(); 601 handleAnaDatePicker();
599 break; 602 break;
600 603
601 case R.id.ll_bike: 604 case R.id.ll_bike:
602 stepType = Const.STEP_TYPE.BIKE; 605 stepType = Const.STEP_TYPE.BIKE;
603 updateUiStepType(true, false, false); 606 updateUiStepType(true, false, false);
604 // add data 607 // add data
605 mDataCurrent = mDataModBike; 608 mDataCurrent = mDataModBike;
606 updateUI(); 609 updateUI();
607 break; 610 break;
608 611
609 case R.id.ll_walking: 612 case R.id.ll_walking:
610 stepType = Const.STEP_TYPE.WALKING; 613 stepType = Const.STEP_TYPE.WALKING;
611 updateUiStepType(false, true, false); 614 updateUiStepType(false, true, false);
612 // add data 615 // add data
613 mDataCurrent = mDataModWalking; 616 mDataCurrent = mDataModWalking;
614 updateUI(); 617 updateUI();
615 break; 618 break;
616 619
617 case R.id.ll_running: 620 case R.id.ll_running:
618 stepType = Const.STEP_TYPE.RUNNING; 621 stepType = Const.STEP_TYPE.RUNNING;
619 updateUiStepType(false, false, true); 622 updateUiStepType(false, false, true);
620 // add 623 // add
621 mDataCurrent = mDataModRunning; 624 mDataCurrent = mDataModRunning;
622 updateUI(); 625 updateUI();
623 break; 626 break;
624 627
625 case R.id.rl_stepView: 628 case R.id.rl_stepView:
626 mHistoryFragment.showDetailFragment(); 629 mHistoryFragment.showDetailFragment();
627 break; 630 break;
628 631
629 default: 632 default:
630 break; 633 break;
631 } 634 }
632 } 635 }
633 636
634 @Override 637 @Override
635 public void onActivityResult(int requestCode, int resultCode, Intent data) { 638 public void onActivityResult(int requestCode, int resultCode, Intent data) {
636 super.onActivityResult(requestCode, resultCode, data); 639 super.onActivityResult(requestCode, resultCode, data);
637 640
638 } 641 }
639 } 642 }
640 643
app/src/main/java/com/dinhcv/lifelogpedometer/activity/HistoryDetailFragment.java
1 package com.dinhcv.lifelogpedometer.activity; 1 package com.dinhcv.lifelogpedometer.activity;
2 2
3 import android.app.DatePickerDialog; 3 import android.app.DatePickerDialog;
4 import android.content.Context; 4 import android.content.Context;
5 import android.os.Bundle; 5 import android.os.Bundle;
6 import android.view.LayoutInflater; 6 import android.view.LayoutInflater;
7 import android.view.View; 7 import android.view.View;
8 import android.view.ViewGroup; 8 import android.view.ViewGroup;
9 import android.widget.Button; 9 import android.widget.Button;
10 import android.widget.DatePicker; 10 import android.widget.DatePicker;
11 import android.widget.EditText; 11 import android.widget.EditText;
12 import android.widget.ImageButton; 12 import android.widget.ImageButton;
13 import android.widget.LinearLayout; 13 import android.widget.LinearLayout;
14 import android.widget.ProgressBar; 14 import android.widget.ProgressBar;
15 import android.widget.TextView; 15 import android.widget.TextView;
16 16
17 import com.dinhcv.lifelogpedometer.R; 17 import com.dinhcv.lifelogpedometer.R;
18 import com.dinhcv.lifelogpedometer.adapter.HistoryAdapter; 18 import com.dinhcv.lifelogpedometer.adapter.HistoryAdapter;
19 import com.dinhcv.lifelogpedometer.customview.ExpandableListCustomView; 19 import com.dinhcv.lifelogpedometer.customview.ExpandableListCustomView;
20 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener; 20 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener;
21 import com.dinhcv.lifelogpedometer.model.structure.history.HistoryInfo; 21 import com.dinhcv.lifelogpedometer.model.structure.history.HistoryInfo;
22 import com.dinhcv.lifelogpedometer.model.structure.history.HistoryItemInfo; 22 import com.dinhcv.lifelogpedometer.model.structure.history.HistoryItemInfo;
23 import com.dinhcv.lifelogpedometer.portal.ApiServices; 23 import com.dinhcv.lifelogpedometer.portal.ApiServices;
24 import com.dinhcv.lifelogpedometer.portal.LLAPIManager; 24 import com.dinhcv.lifelogpedometer.portal.LLAPIManager;
25 import com.dinhcv.lifelogpedometer.utils.Const; 25 import com.dinhcv.lifelogpedometer.utils.Const;
26 import com.dinhcv.lifelogpedometer.utils.Debug; 26 import com.dinhcv.lifelogpedometer.utils.Debug;
27 import com.dinhcv.lifelogpedometer.utils.Utils; 27 import com.dinhcv.lifelogpedometer.utils.Utils;
28 28
29 import org.json.JSONException; 29 import org.json.JSONException;
30 import org.json.JSONObject; 30 import org.json.JSONObject;
31 31
32 import java.util.ArrayList; 32 import java.util.ArrayList;
33 import java.util.Calendar; 33 import java.util.Calendar;
34 import java.util.Date; 34 import java.util.Date;
35 import java.util.HashMap; 35 import java.util.HashMap;
36 import java.util.List; 36 import java.util.List;
37 import java.util.Map; 37 import java.util.Map;
38 38
39 import butterknife.BindView; 39 import butterknife.BindView;
40 import butterknife.ButterKnife; 40 import butterknife.ButterKnife;
41 import butterknife.OnClick; 41 import butterknife.OnClick;
42 import retrofit2.Callback; 42 import retrofit2.Callback;
43 43
44 44
45 public class HistoryDetailFragment extends FragmentBase { 45 public class HistoryDetailFragment extends FragmentBase {
46 private View mRootView; 46 private View mRootView;
47 47
48 @BindView(R.id.btn_left_date) 48 @BindView(R.id.btn_left_date)
49 ImageButton btnLeftDate; 49 ImageButton btnLeftDate;
50 @BindView(R.id.btn_right_date) 50 @BindView(R.id.btn_right_date)
51 ImageButton btnRightDate; 51 ImageButton btnRightDate;
52 @BindView(R.id.tv_date) 52 @BindView(R.id.tv_date)
53 TextView tvDate; 53 TextView tvDate;
54 @BindView(R.id.tv_week_day) 54 @BindView(R.id.tv_week_day)
55 TextView tvWeekDay; 55 TextView tvWeekDay;
56 @BindView(R.id.ll_bike) 56 @BindView(R.id.ll_bike)
57 LinearLayout llBike; 57 LinearLayout llBike;
58 @BindView(R.id.ll_walking) 58 @BindView(R.id.ll_walking)
59 LinearLayout llWalking; 59 LinearLayout llWalking;
60 @BindView(R.id.ll_running) 60 @BindView(R.id.ll_running)
61 LinearLayout llRunning; 61 LinearLayout llRunning;
62 @BindView(R.id.lv_history) 62 @BindView(R.id.lv_history)
63 ExpandableListCustomView lvHistory; 63 ExpandableListCustomView lvHistory;
64 private HistoryAdapter mHistoreAdapter; 64 private HistoryAdapter mHistoreAdapter;
65 65
66 66
67 @BindView(R.id.btn_sixMonth) 67 @BindView(R.id.btn_sixMonth)
68 Button btnSixMonth; 68 Button btnSixMonth;
69 @BindView(R.id.btn_oneDay) 69 @BindView(R.id.btn_oneDay)
70 Button btnOneDay; 70 Button btnOneDay;
71 @BindView(R.id.btn_oneWeek) 71 @BindView(R.id.btn_oneWeek)
72 Button btnOneWeek; 72 Button btnOneWeek;
73 @BindView(R.id.btn_oneMonth) 73 @BindView(R.id.btn_oneMonth)
74 Button btnOneMonth; 74 Button btnOneMonth;
75 @BindView(R.id.btn_threeMonth) 75 @BindView(R.id.btn_threeMonth)
76 Button btnThreeMonth; 76 Button btnThreeMonth;
77 77
78 private Date mAnaDate; 78 private Date mAnaDate;
79 private Calendar mCalendar; 79 private Calendar mCalendar;
80 80
81 private int mAnaDay; 81 private int mAnaDay;
82 private int mAnaMonth; 82 private int mAnaMonth;
83 private int mAnaYear; 83 private int mAnaYear;
84 private Context mContext; 84 private Context mContext;
85 private Const.DATA_TYPE dataType; 85 private Const.DATA_TYPE dataType;
86 private Const.STEP_TYPE stepType; 86 private Const.STEP_TYPE stepType;
87 87
88 private List<HistoryItemInfo> mDataModWalking = new ArrayList<>(); 88 private List<HistoryItemInfo> mDataModWalking = new ArrayList<>();
89 private List<HistoryItemInfo> mDataModRunning = new ArrayList<>(); 89 private List<HistoryItemInfo> mDataModRunning = new ArrayList<>();
90 private List<HistoryItemInfo> mDataModBike = new ArrayList<>(); 90 private List<HistoryItemInfo> mDataModBike = new ArrayList<>();
91 private List<HistoryItemInfo> mDataCurrent = new ArrayList<>(); 91 private List<HistoryItemInfo> mDataCurrent = new ArrayList<>();
92 92
93 private HistoryFragment mHistoryFragment; 93 private HistoryFragment mHistoryFragment;
94 94
95 public void setRootFragment(HistoryFragment frag) { 95 public void setRootFragment(HistoryFragment frag) {
96 this.mHistoryFragment = frag; 96 this.mHistoryFragment = frag;
97 } 97 }
98 98
99 @Override 99 @Override
100 public View onCreateView(final LayoutInflater inflater,final ViewGroup container, 100 public View onCreateView(final LayoutInflater inflater,final ViewGroup container,
101 final Bundle savedInstanceState) { 101 final Bundle savedInstanceState) {
102 // Inflate the layout for this fragment 102 // Inflate the layout for this fragment
103 mRootView = inflater.inflate(R.layout.fragment_history_detail, null); 103 mRootView = inflater.inflate(R.layout.fragment_history_detail, null);
104 ButterKnife.bind(this, mRootView); 104 ButterKnife.bind(this, mRootView);
105 mContext = getActivity(); 105 mContext = getActivity();
106 initView(); 106 initView();
107 initData(); 107 initData();
108 108
109 return mRootView; 109 return mRootView;
110 } 110 }
111 111
112 private void initView() { 112 private void initView() {
113 113
114 } 114 }
115 115
116 /** 116 /**
117 * init data for 117 * init data for
118 */ 118 */
119 private void initData() { 119 private void initData() {
120 mCalendar = Calendar.getInstance(); 120 mCalendar = Calendar.getInstance();
121 mCalendar.setTime(new Date()); 121 mCalendar.setTime(new Date());
122 mAnaDate = mCalendar.getTime(); 122 mAnaDate = mCalendar.getTime();
123 mAnaYear = mCalendar.get(Calendar.YEAR); 123 mAnaYear = mCalendar.get(Calendar.YEAR);
124 mAnaMonth = mCalendar.get(Calendar.MONTH); 124 mAnaMonth = mCalendar.get(Calendar.MONTH);
125 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH); 125 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH);
126 126
127 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate)); 127 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate));
128 tvWeekDay.setText(Utils.getWeekdayFromDate(mAnaDate)); 128 tvWeekDay.setText(Utils.getWeekdayFromDate(mAnaDate));
129 129
130 dataType = Const.DATA_TYPE.ONE_DAY; 130 dataType = Const.DATA_TYPE.ONE_DAY;
131 stepType = Const.STEP_TYPE.WALKING; 131 stepType = Const.STEP_TYPE.WALKING;
132 updateUiType(); 132 updateUiType();
133 updateUiStepType(false, true, false); 133 updateUiStepType(false, true, false);
134 134
135 getHistoryDetail(dataType, mAnaDate); 135 getHistoryDetail(dataType, mAnaDate);
136 } 136 }
137 137
138 138
139 /** 139 /**
140 * Show date picker dialog 140 * Show date picker dialog
141 */ 141 */
142 private void handleAnaDatePicker() { 142 private void handleAnaDatePicker() {
143 143
144 new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() { 144 new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
145 @Override 145 @Override
146 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 146 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
147 147
148 mCalendar = Calendar.getInstance(); 148 mCalendar = Calendar.getInstance();
149 mCalendar.set(year, monthOfYear, dayOfMonth); 149 mCalendar.set(year, monthOfYear, dayOfMonth);
150 mAnaYear = year; 150 mAnaYear = year;
151 mAnaMonth = monthOfYear; 151 mAnaMonth = monthOfYear;
152 mAnaDay = dayOfMonth; 152 mAnaDay = dayOfMonth;
153 Date date = mCalendar.getTime(); 153 Date date = mCalendar.getTime();
154 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 154 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
155 tvWeekDay.setText(Utils.getWeekdayFromDate(date)); 155 tvWeekDay.setText(Utils.getWeekdayFromDate(date));
156 mAnaDate = date; 156 mAnaDate = date;
157 getHistoryDetail(dataType, mAnaDate); 157 getHistoryDetail(dataType, mAnaDate);
158 } 158 }
159 }, mAnaYear, mAnaMonth, mAnaDay).show(); 159 }, mAnaYear, mAnaMonth, mAnaDay).show();
160 160
161 } 161 }
162 162
163 private void updateUiType() { 163 private void updateUiType() {
164 if (dataType == Const.DATA_TYPE.ONE_DAY) { 164 if (dataType == Const.DATA_TYPE.ONE_DAY) {
165 setButtonSelected(true, false, false, false, false); 165 setButtonSelected(true, false, false, false, false);
166 } else if (dataType == Const.DATA_TYPE.ONE_WEEK) { 166 } else if (dataType == Const.DATA_TYPE.ONE_WEEK) {
167 setButtonSelected(false, true, false, false, false); 167 setButtonSelected(false, true, false, false, false);
168 } else if (dataType == Const.DATA_TYPE.ONE_MONTH) { 168 } else if (dataType == Const.DATA_TYPE.ONE_MONTH) {
169 setButtonSelected(false, false, true, false, false); 169 setButtonSelected(false, false, true, false, false);
170 } else if (dataType == Const.DATA_TYPE.THREE_MONTH){ 170 } else if (dataType == Const.DATA_TYPE.THREE_MONTH){
171 setButtonSelected(false, false, false, true, false); 171 setButtonSelected(false, false, false, true, false);
172 } else if (dataType == Const.DATA_TYPE.SIX_MONTH){ 172 } else if (dataType == Const.DATA_TYPE.SIX_MONTH){
173 setButtonSelected(false, false, false, false, true); 173 setButtonSelected(false, false, false, false, true);
174 } 174 }
175 } 175 }
176 176
177 private void setButtonSelected(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5 ) { 177 private void setButtonSelected(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5 ) {
178 btnOneDay.setSelected(b1); 178 btnOneDay.setSelected(b1);
179 btnOneWeek.setSelected(b2); 179 btnOneWeek.setSelected(b2);
180 btnOneMonth.setSelected(b3); 180 btnOneMonth.setSelected(b3);
181 btnThreeMonth.setSelected(b4); 181 btnThreeMonth.setSelected(b4);
182 btnSixMonth.setSelected(b5); 182 btnSixMonth.setSelected(b5);
183 } 183 }
184 184
185 private void updateUiStepType(boolean b1, boolean b2, boolean b3) { 185 private void updateUiStepType(boolean b1, boolean b2, boolean b3) {
186 llBike.setSelected(b1); 186 llBike.setSelected(b1);
187 llWalking.setSelected(b2); 187 llWalking.setSelected(b2);
188 llRunning.setSelected(b3); 188 llRunning.setSelected(b3);
189 } 189 }
190 190
191 private void updateUI(){ 191 private void updateUI(){
192 // get data server 192 // get data server
193 if (mDataCurrent != null && mDataCurrent.size() >0){ 193 if (mDataCurrent != null && mDataCurrent.size() >0){
194 mHistoreAdapter = new HistoryAdapter(mContext, mDataCurrent); 194 mHistoreAdapter = new HistoryAdapter(mContext, mDataCurrent);
195 lvHistory.setAdapter(mHistoreAdapter); 195 lvHistory.setAdapter(mHistoreAdapter);
196 lvHistory.setExpanded(true); 196 lvHistory.setExpanded(true);
197 } 197 }
198 } 198 }
199 199
200 private void getHistoryDetail(Const.DATA_TYPE dataType, Date toDate){ 200 private void getHistoryDetail(Const.DATA_TYPE dataType, Date toDate){
201 Date fromDate = Utils.getFromDate(mAnaDate, dataType); 201 Date fromDate = Utils.getFromDate(mAnaDate, dataType);
202 202
203 showDialog(mContext); 203 showDialog(mContext);
204 ApiServices.historyDetail(fromDate, toDate, new LLAPIManagerListener() { 204 ApiServices.historyDetail(fromDate, toDate, new LLAPIManagerListener() {
205 @Override 205 @Override
206 public void onError(Error error) { 206 public void onError(Error error) {
207 Debug.error("Get data history error"); 207 Debug.error("Get data history error");
208 hiddenDialog(); 208 hiddenDialog();
209 showDialogNotData(); 209 showDialogNotData();
210 } 210 }
211 211
212 @Override 212 @Override
213 public void onSuccess(String json) { 213 public void onSuccess(String json) {
214 Debug.error("Get data history success"); 214 Debug.error("Get data history success");
215 hiddenDialog(); 215 hiddenDialog();
216 loadDataDone(json); 216 loadDataDone(json);
217 } 217 }
218 218
219 @Override 219 @Override
220 public void onSuccess(JSONObject object) { 220 public void onSuccess(JSONObject object) {
221 Debug.error("Get data history success"); 221 Debug.error("Get data history success");
222 hiddenDialog(); 222 hiddenDialog();
223 } 223 }
224 }); 224 });
225 } 225 }
226 226
227 private void showDialogNotData(){ 227 private void showDialogNotData(){
228 showAlerDialog(mContext, getResources().getString(R.string.can_not_get_data)); 228 showAlerDialog(mContext, getResources().getString(R.string.can_not_get_data));
229 } 229 }
230 230
231 private void loadDataDone(String jsonString) { 231 private void loadDataDone(String jsonString) {
232 JSONObject jsonObject = null; 232 JSONObject jsonObject = null;
233 try { 233 try {
234 jsonObject = new JSONObject(jsonString); 234 jsonObject = new JSONObject(jsonString);
235 int status = jsonObject.optInt("status"); 235 int status = jsonObject.optInt("status");
236 if (status == 1) { 236 if (status == 1) {
237 JSONObject jsonObject1 = jsonObject.optJSONObject("result"); 237 JSONObject jsonObject1 = jsonObject.optJSONObject("result");
238 JSONObject jsonMod1 = jsonObject1.getJSONObject("mode_1"); 238 JSONObject jsonMod1 = jsonObject1.optJSONObject("mode_1");
239 JSONObject jsonMod2 = jsonObject1.getJSONObject("mode_2"); 239 JSONObject jsonMod2 = jsonObject1.optJSONObject("mode_2");
240 JSONObject jsonMod3 = jsonObject1.getJSONObject("mode_3"); 240 JSONObject jsonMod3 = jsonObject1.optJSONObject("mode_3");
241 //addDataModWalking(jsonMod1); 241 //addDataModWalking(jsonMod1);
242 //addDataModRunning(jsonMod2); 242 //addDataModRunning(jsonMod2);
243 //addDataModBike(jsonMod3); 243 //addDataModBike(jsonMod3);
244 244
245 } 245 }
246 } catch (JSONException e) { 246 } catch (JSONException e) {
247 e.printStackTrace(); 247 e.printStackTrace();
248 mDataModWalking.clear(); 248 mDataModWalking.clear();
249 mDataModRunning.clear();; 249 mDataModRunning.clear();;
250 mDataModBike.clear();; 250 mDataModBike.clear();;
251 } 251 }
252 252
253 if (stepType == Const.STEP_TYPE.WALKING){ 253 if (stepType == Const.STEP_TYPE.WALKING){
254 mDataCurrent = mDataModWalking; 254 mDataCurrent = mDataModWalking;
255 }else if (stepType == Const.STEP_TYPE.RUNNING){ 255 }else if (stepType == Const.STEP_TYPE.RUNNING){
256 mDataCurrent = mDataModRunning; 256 mDataCurrent = mDataModRunning;
257 }else { 257 }else {
258 mDataCurrent = mDataModBike; 258 mDataCurrent = mDataModBike;
259 } 259 }
260 260
261 updateUI(); 261 updateUI();
262 } 262 }
263 263
264 @OnClick({R.id.tv_date, R.id.btn_left_date, R.id.btn_right_date, R.id.btn_oneDay, R.id.btn_oneWeek, 264 @OnClick({R.id.tv_date, R.id.btn_left_date, R.id.btn_right_date, R.id.btn_oneDay, R.id.btn_oneWeek,
265 R.id.btn_oneMonth, R.id.btn_threeMonth, R.id.btn_sixMonth, R.id.ll_walking, R.id.ll_bike, 265 R.id.btn_oneMonth, R.id.btn_threeMonth, R.id.btn_sixMonth, R.id.ll_walking, R.id.ll_bike,
266 R.id.ll_running}) 266 R.id.ll_running})
267 public void onClick(View view){ 267 public void onClick(View view){
268 Date date; 268 Date date;
269 switch (view.getId()){ 269 switch (view.getId()){
270 case R.id.tv_date: 270 case R.id.tv_date:
271 handleAnaDatePicker(); 271 handleAnaDatePicker();
272 break; 272 break;
273 case R.id.btn_left_date: 273 case R.id.btn_left_date:
274 mCalendar = Calendar.getInstance(); 274 mCalendar = Calendar.getInstance();
275 mCalendar.setTime(mAnaDate); 275 mCalendar.setTime(mAnaDate);
276 mCalendar.add(Calendar.DAY_OF_MONTH, -1); 276 mCalendar.add(Calendar.DAY_OF_MONTH, -1);
277 date = mCalendar.getTime(); 277 date = mCalendar.getTime();
278 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 278 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
279 tvWeekDay.setText(Utils.getWeekdayFromDate(date)); 279 tvWeekDay.setText(Utils.getWeekdayFromDate(date));
280 mAnaDate = date; 280 mAnaDate = date;
281 getHistoryDetail(dataType, mAnaDate); 281 getHistoryDetail(dataType, mAnaDate);
282 break; 282 break;
283 283
284 case R.id.btn_right_date: 284 case R.id.btn_right_date:
285 mCalendar = Calendar.getInstance(); 285 mCalendar = Calendar.getInstance();
286 mCalendar.setTime(mAnaDate); 286 mCalendar.setTime(mAnaDate);
287 mCalendar.add(Calendar.DAY_OF_MONTH, +1); 287 mCalendar.add(Calendar.DAY_OF_MONTH, +1);
288 date = mCalendar.getTime(); 288 date = mCalendar.getTime();
289 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 289 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
290 tvWeekDay.setText(Utils.getWeekdayFromDate(date)); 290 tvWeekDay.setText(Utils.getWeekdayFromDate(date));
291 mAnaDate = date; 291 mAnaDate = date;
292 getHistoryDetail(dataType, mAnaDate); 292 getHistoryDetail(dataType, mAnaDate);
293 break; 293 break;
294 294
295 case R.id.btn_oneDay: 295 case R.id.btn_oneDay:
296 dataType = Const.DATA_TYPE.ONE_DAY; 296 dataType = Const.DATA_TYPE.ONE_DAY;
297 updateUiType(); 297 updateUiType();
298 getHistoryDetail(dataType, mAnaDate); 298 getHistoryDetail(dataType, mAnaDate);
299 break; 299 break;
300 300
301 case R.id.btn_oneWeek: 301 case R.id.btn_oneWeek:
302 dataType = Const.DATA_TYPE.ONE_WEEK; 302 dataType = Const.DATA_TYPE.ONE_WEEK;
303 updateUiType(); 303 updateUiType();
304 getHistoryDetail(dataType, mAnaDate); 304 getHistoryDetail(dataType, mAnaDate);
305 break; 305 break;
306 306
307 case R.id.btn_oneMonth: 307 case R.id.btn_oneMonth:
308 dataType = Const.DATA_TYPE.ONE_MONTH; 308 dataType = Const.DATA_TYPE.ONE_MONTH;
309 updateUiType(); 309 updateUiType();
310 getHistoryDetail(dataType, mAnaDate); 310 getHistoryDetail(dataType, mAnaDate);
311 break; 311 break;
312 312
313 case R.id.btn_threeMonth: 313 case R.id.btn_threeMonth:
314 dataType = Const.DATA_TYPE.THREE_MONTH; 314 dataType = Const.DATA_TYPE.THREE_MONTH;
315 updateUiType(); 315 updateUiType();
316 getHistoryDetail(dataType, mAnaDate); 316 getHistoryDetail(dataType, mAnaDate);
317 break; 317 break;
318 318
319 case R.id.btn_sixMonth: 319 case R.id.btn_sixMonth:
320 dataType = Const.DATA_TYPE.SIX_MONTH; 320 dataType = Const.DATA_TYPE.SIX_MONTH;
321 updateUiType(); 321 updateUiType();
322 getHistoryDetail(dataType, mAnaDate); 322 getHistoryDetail(dataType, mAnaDate);
323 break; 323 break;
324 324
325 case R.id.ll_walking: 325 case R.id.ll_walking:
326 stepType = Const.STEP_TYPE.WALKING; 326 stepType = Const.STEP_TYPE.WALKING;
327 updateUiStepType(false, true, false); 327 updateUiStepType(false, true, false);
328 // add data 328 // add data
329 mDataCurrent = mDataModWalking; 329 mDataCurrent = mDataModWalking;
330 updateUI(); 330 updateUI();
331 break; 331 break;
332 332
333 case R.id.ll_running: 333 case R.id.ll_running:
334 stepType = Const.STEP_TYPE.RUNNING; 334 stepType = Const.STEP_TYPE.RUNNING;
335 updateUiStepType(false, false, true); 335 updateUiStepType(false, false, true);
336 // add 336 // add
337 mDataCurrent = mDataModRunning; 337 mDataCurrent = mDataModRunning;
338 updateUI(); 338 updateUI();
339 break; 339 break;
340 340
341 case R.id.ll_bike: 341 case R.id.ll_bike:
342 stepType = Const.STEP_TYPE.BIKE; 342 stepType = Const.STEP_TYPE.BIKE;
343 updateUiStepType(true, false, false); 343 updateUiStepType(true, false, false);
344 // add data 344 // add data
345 mDataCurrent = mDataModBike; 345 mDataCurrent = mDataModBike;
346 updateUI(); 346 updateUI();
347 break; 347 break;
348 348
349 default: 349 default:
350 break; 350 break;
351 351
352 } 352 }
353 } 353 }
354 354
355 355
356 } 356 }
357 357
app/src/main/java/com/dinhcv/lifelogpedometer/activity/TopTodayFragment.java
1 package com.dinhcv.lifelogpedometer.activity; 1 package com.dinhcv.lifelogpedometer.activity;
2 2
3 import android.app.DatePickerDialog; 3 import android.app.DatePickerDialog;
4 import android.app.ProgressDialog; 4 import android.app.ProgressDialog;
5 import android.content.Context; 5 import android.content.Context;
6 import android.graphics.Color; 6 import android.graphics.Color;
7 import android.hardware.Sensor; 7 import android.hardware.Sensor;
8 import android.hardware.SensorEvent; 8 import android.hardware.SensorEvent;
9 import android.hardware.SensorEventListener; 9 import android.hardware.SensorEventListener;
10 import android.hardware.SensorManager; 10 import android.hardware.SensorManager;
11 import android.os.Bundle; 11 import android.os.Bundle;
12 import android.support.annotation.Nullable; 12 import android.support.annotation.Nullable;
13 import android.view.LayoutInflater; 13 import android.view.LayoutInflater;
14 import android.view.Menu; 14 import android.view.Menu;
15 import android.view.MenuInflater; 15 import android.view.MenuInflater;
16 import android.view.View; 16 import android.view.View;
17 import android.view.ViewGroup; 17 import android.view.ViewGroup;
18 import android.widget.DatePicker; 18 import android.widget.DatePicker;
19 import android.widget.ImageView; 19 import android.widget.ImageView;
20 import android.widget.LinearLayout; 20 import android.widget.LinearLayout;
21 import android.widget.TextView; 21 import android.widget.TextView;
22 import android.widget.Toast; 22 import android.widget.Toast;
23 23
24 import com.dinhcv.lifelogpedometer.R; 24 import com.dinhcv.lifelogpedometer.R;
25 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener; 25 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener;
26 import com.dinhcv.lifelogpedometer.interfaces.StepListener;
26 import com.dinhcv.lifelogpedometer.model.StepModel; 27 import com.dinhcv.lifelogpedometer.model.StepModel;
27 import com.dinhcv.lifelogpedometer.model.structure.top.StepItemInfo; 28 import com.dinhcv.lifelogpedometer.model.structure.top.StepItemInfo;
28 import com.dinhcv.lifelogpedometer.model.structure.top.TopInfo; 29 import com.dinhcv.lifelogpedometer.model.structure.top.TopInfo;
29 import com.dinhcv.lifelogpedometer.portal.ApiServices; 30 import com.dinhcv.lifelogpedometer.portal.ApiServices;
30 import com.dinhcv.lifelogpedometer.portal.LLAPIManager; 31 import com.dinhcv.lifelogpedometer.portal.LLAPIManager;
31 import com.dinhcv.lifelogpedometer.utils.Const; 32 import com.dinhcv.lifelogpedometer.utils.Const;
32 import com.dinhcv.lifelogpedometer.utils.DayAxisValueFormatter; 33 import com.dinhcv.lifelogpedometer.utils.DayAxisValueFormatter;
33 import com.dinhcv.lifelogpedometer.utils.Debug; 34 import com.dinhcv.lifelogpedometer.utils.Debug;
35 import com.dinhcv.lifelogpedometer.utils.SimpleStepDetector;
34 import com.dinhcv.lifelogpedometer.utils.Utils; 36 import com.dinhcv.lifelogpedometer.utils.Utils;
35 import com.github.mikephil.charting.components.XAxis; 37 import com.github.mikephil.charting.components.XAxis;
36 import com.github.mikephil.charting.components.YAxis; 38 import com.github.mikephil.charting.components.YAxis;
37 39
38 import com.github.mikephil.charting.charts.BarChart; 40 import com.github.mikephil.charting.charts.BarChart;
39 import com.github.mikephil.charting.data.BarData; 41 import com.github.mikephil.charting.data.BarData;
40 import com.github.mikephil.charting.data.BarDataSet; 42 import com.github.mikephil.charting.data.BarDataSet;
41 import com.github.mikephil.charting.data.BarEntry; 43 import com.github.mikephil.charting.data.BarEntry;
42 import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; 44 import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
43 45
44 import org.eazegraph.lib.charts.PieChart; 46 import org.eazegraph.lib.charts.PieChart;
45 import org.eazegraph.lib.models.PieModel; 47 import org.eazegraph.lib.models.PieModel;
46 import org.json.JSONArray; 48 import org.json.JSONArray;
47 import org.json.JSONException; 49 import org.json.JSONException;
48 import org.json.JSONObject; 50 import org.json.JSONObject;
49 51
50 import java.text.NumberFormat; 52 import java.text.NumberFormat;
51 import java.util.ArrayList; 53 import java.util.ArrayList;
52 import java.util.Arrays; 54 import java.util.Arrays;
53 import java.util.Calendar; 55 import java.util.Calendar;
54 import java.util.Date; 56 import java.util.Date;
55 import java.util.List; 57 import java.util.List;
56 import java.util.Locale; 58 import java.util.Locale;
57 59
58 import static com.github.mikephil.charting.utils.ColorTemplate.rgb; 60 import static com.github.mikephil.charting.utils.ColorTemplate.rgb;
59 61
60 62
61 public class TopTodayFragment extends FragmentBase implements SettingFragmentPresenter, SensorEventListener { 63 public class TopTodayFragment extends FragmentBase implements SettingFragmentPresenter, SensorEventListener, StepListener {
62 64
63 private TextView stepsView; 65 private TextView stepsView;
64 private TextView tvStepGoal; 66 private TextView tvStepGoal;
65 private TextView tvDistance; 67 private TextView tvDistance;
66 private TextView tvTime; 68 private TextView tvTime;
67 private TextView tvStepRemain; 69 private TextView tvStepRemain;
68 private TextView tvStepRateDone; 70 private TextView tvStepRateDone;
69 private boolean showSteps = true; 71 private boolean showSteps = true;
70 private PieModel sliceGoal, sliceCurrent; 72 private PieModel sliceGoal, sliceCurrent;
71 private PieChart pg; 73 private PieChart pg;
72 private TextView tvDate; 74 private TextView tvDate;
73 private ImageView ivBack; 75 private ImageView ivBack;
74 private ImageView ivNext; 76 private ImageView ivNext;
75 77
76 private LinearLayout llBike; 78 private LinearLayout llBike;
77 private LinearLayout llWalking; 79 private LinearLayout llWalking;
78 private LinearLayout llRunning; 80 private LinearLayout llRunning;
79 private Const.STEP_TYPE stepType; 81 private Const.STEP_TYPE stepType;
80 82
81 private Date mAnaDate; 83 private Date mAnaDate;
82 private Calendar mCalendar; 84 private Calendar mCalendar;
83 85
84 private int mAnaDay; 86 private int mAnaDay;
85 private int mAnaMonth; 87 private int mAnaMonth;
86 private int mAnaYear; 88 private int mAnaYear;
87 89
88 public static int STEP_SIZE = 75; 90 public static int STEP_SIZE = 75;
89 private StepModel mStepModel; 91 private StepModel mStepModel;
90 private TextView tvSmallStepGoal; 92 private TextView tvSmallStepGoal;
91 private TextView tvSmallRemain; 93 private TextView tvSmallRemain;
92 private Context mContext; 94 private Context mContext;
93 95
94 public final static NumberFormat formatter = NumberFormat.getInstance(Locale.getDefault()); 96 public final static NumberFormat formatter = NumberFormat.getInstance(Locale.getDefault());
95 private SensorManager sensorManager; 97 private SensorManager sensorManager;
96 private boolean activityRunning; 98 private boolean activityRunning;
97 private int stepTotal = 0; 99 private int stepTotal = 0;
98 private int stepGoal = 0; 100 private int stepGoal = 0;
99 private int stepCount = 0; 101 private int stepCount = 0;
100 102
101 private Date mFromDate; 103 private Date mFromDate;
102 private Date mToDate; 104 private Date mToDate;
103 105
104 private TopInfo mTopInfo = new TopInfo(); 106 private TopInfo mTopInfo = new TopInfo();
105 private BarChart mChart; 107 private BarChart mChart;
106 108
107 private List<String> dateList; 109 private List<String> dateList;
108 private String[] mParties; 110 private String[] mParties;
109 private Integer[] mStep; 111 private Integer[] mStep;
110 private ProgressDialog progress; 112 private ProgressDialog progress;
113 private boolean isAccelo = false;
114 private boolean isBusy = false;
115 private SimpleStepDetector simpleStepDetector;
111 116
112 private TopFragment mTopFragment; 117 private TopFragment mTopFragment;
113 public void setRootFragment(TopFragment frag) { 118 public void setRootFragment(TopFragment frag) {
114 this.mTopFragment = frag; 119 this.mTopFragment = frag;
115 } 120 }
116 121
117 @Override 122 @Override
118 public void onCreate(final Bundle savedInstanceState) { 123 public void onCreate(final Bundle savedInstanceState) {
119 super.onCreate(savedInstanceState); 124 super.onCreate(savedInstanceState);
120 setHasOptionsMenu(true); 125 setHasOptionsMenu(true);
126
121 } 127 }
122 128
123 @Override 129 @Override
124 public View onCreateView(final LayoutInflater inflater, final ViewGroup container, 130 public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
125 final Bundle savedInstanceState) { 131 final Bundle savedInstanceState) {
126 final View v = inflater.inflate(R.layout.fragment_top_today, null); 132 final View v = inflater.inflate(R.layout.fragment_top_today, null);
127 mContext = getActivity(); 133 mContext = getActivity();
128 sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); 134 sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
129 135
136 simpleStepDetector = new SimpleStepDetector();
137 simpleStepDetector.registerListener(this);
138
130 initView(v); 139 initView(v);
131 140
132 // slice for the steps taken today 141 // slice for the steps taken today
133 sliceCurrent = new PieModel("", 0, Color.parseColor("#6FE7F7")); 142 sliceCurrent = new PieModel("", 0, Color.parseColor("#6FE7F7"));
134 pg.addPieSlice(sliceCurrent); 143 pg.addPieSlice(sliceCurrent);
135 144
136 // slice for the "missing" steps until reaching the goal 145 // slice for the "missing" steps until reaching the goal
137 sliceGoal = new PieModel("", Const.STEP_GOAL, Color.parseColor("#B7B8B6")); 146 sliceGoal = new PieModel("", Const.STEP_GOAL, Color.parseColor("#B7B8B6"));
138 pg.addPieSlice(sliceGoal); 147 pg.addPieSlice(sliceGoal);
139 148
140 pg.setDrawValueInPie(false); 149 pg.setDrawValueInPie(false);
141 pg.setUsePieRotation(false); 150 pg.setUsePieRotation(false);
142 pg.startAnimation(); 151 pg.startAnimation();
143 pg.setAutoCenterInSlice(false); 152 pg.setAutoCenterInSlice(false);
144 153
145 mCalendar = Calendar.getInstance(); 154 mCalendar = Calendar.getInstance();
146 mCalendar.setTime(new Date()); 155 mCalendar.setTime(new Date());
147 mAnaDate = mCalendar.getTime(); 156 mAnaDate = mCalendar.getTime();
148 mAnaYear = mCalendar.get(Calendar.YEAR); 157 mAnaYear = mCalendar.get(Calendar.YEAR);
149 mAnaMonth = mCalendar.get(Calendar.MONTH); 158 mAnaMonth = mCalendar.get(Calendar.MONTH);
150 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH); 159 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH);
151 160
152 mFromDate = new Date(); 161 mFromDate = new Date();
153 162
154 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate)); 163 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate));
155 164
156 initData(); 165 initData();
157 166
158 handleEvent(); 167 handleEvent();
159 168
160 getTopPage(mAnaDate, stepType); 169 getTopPage(mAnaDate, stepType);
161 170
162 return v; 171 return v;
163 } 172 }
164 173
165 private void initView(View v){ 174 private void initView(View v){
166 stepsView = (TextView) v.findViewById(R.id.steps); 175 stepsView = (TextView) v.findViewById(R.id.steps);
167 tvDistance = (TextView) v.findViewById(R.id.tv_distance); 176 tvDistance = (TextView) v.findViewById(R.id.tv_distance);
168 tvStepGoal = (TextView) v.findViewById(R.id.tv_stepGoal); 177 tvStepGoal = (TextView) v.findViewById(R.id.tv_stepGoal);
169 tvStepRemain = (TextView) v.findViewById(R.id.tv_stepRemain); 178 tvStepRemain = (TextView) v.findViewById(R.id.tv_stepRemain);
170 tvStepRateDone = (TextView) v.findViewById(R.id.tv_stepRateDone); 179 tvStepRateDone = (TextView) v.findViewById(R.id.tv_stepRateDone);
171 tvSmallStepGoal = (TextView) v.findViewById(R.id.tv_smallStepGoal); 180 tvSmallStepGoal = (TextView) v.findViewById(R.id.tv_smallStepGoal);
172 tvSmallRemain = (TextView) v.findViewById(R.id.tv_smallRemain); 181 tvSmallRemain = (TextView) v.findViewById(R.id.tv_smallRemain);
173 tvTime = (TextView) v.findViewById(R.id.tv_time); 182 tvTime = (TextView) v.findViewById(R.id.tv_time);
174 tvDate = (TextView) v.findViewById(R.id.tv_date); 183 tvDate = (TextView) v.findViewById(R.id.tv_date);
175 ivBack = (ImageView) v.findViewById(R.id.iv_back); 184 ivBack = (ImageView) v.findViewById(R.id.iv_back);
176 ivNext = (ImageView) v.findViewById(R.id.iv_next); 185 ivNext = (ImageView) v.findViewById(R.id.iv_next);
177 186
178 mChart = (BarChart) v.findViewById(R.id.chart); 187 mChart = (BarChart) v.findViewById(R.id.chart);
179 pg = (PieChart) v.findViewById(R.id.graph); 188 pg = (PieChart) v.findViewById(R.id.graph);
180 189
181 llRunning = (LinearLayout) v.findViewById(R.id.ll_running); 190 llRunning = (LinearLayout) v.findViewById(R.id.ll_running);
182 llWalking = (LinearLayout) v.findViewById(R.id.ll_walking); 191 llWalking = (LinearLayout) v.findViewById(R.id.ll_walking);
183 llBike = (LinearLayout) v.findViewById(R.id.ll_bike); 192 llBike = (LinearLayout) v.findViewById(R.id.ll_bike);
184 } 193 }
185 194
186 private void initData(){ 195 private void initData(){
187 mCalendar = Calendar.getInstance(); 196 mCalendar = Calendar.getInstance();
188 mCalendar.setTime(new Date()); 197 mCalendar.setTime(new Date());
189 mAnaDate = mCalendar.getTime(); 198 mAnaDate = mCalendar.getTime();
190 mAnaYear = mCalendar.get(Calendar.YEAR); 199 mAnaYear = mCalendar.get(Calendar.YEAR);
191 mAnaMonth = mCalendar.get(Calendar.MONTH); 200 mAnaMonth = mCalendar.get(Calendar.MONTH);
192 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH); 201 mAnaDay = mCalendar.get(Calendar.DAY_OF_MONTH);
193 202
194 203
195 stepType = Const.STEP_TYPE.WALKING; 204 stepType = Const.STEP_TYPE.WALKING;
196 updateUiStepType(false, true, false); 205 updateUiStepType(false, true, false);
197 206
198 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate)); 207 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(mAnaDate));
199 } 208 }
200 209
201 private void updateUiStepType(boolean b1, boolean b2, boolean b3) { 210 private void updateUiStepType(boolean b1, boolean b2, boolean b3) {
202 llBike.setSelected(b1); 211 llBike.setSelected(b1);
203 llWalking.setSelected(b2); 212 llWalking.setSelected(b2);
204 llRunning.setSelected(b3); 213 llRunning.setSelected(b3);
205 } 214 }
206 215
207 private void stepsDistanceChanged() { 216 private void stepsDistanceChanged() {
208 if (progress != null){ 217 if (progress != null){
209 progress.dismiss(); 218 progress.dismiss();
210 } 219 }
211 updatePie(); 220 updatePie();
212 updateBars(); 221 updateBars();
213 } 222 }
214 223
215 224
216 @Override 225 @Override
217 public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { 226 public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
218 inflater.inflate(R.menu.main, menu); 227 inflater.inflate(R.menu.main, menu);
219 } 228 }
220 229
221 private void getTopPage(Date date, Const.STEP_TYPE stepType){ 230 private void getTopPage(Date date, Const.STEP_TYPE stepType){
222 231
223 progress = new ProgressDialog(mContext); 232 progress = new ProgressDialog(mContext);
224 progress.setMessage(getString(R.string.loading)); 233 progress.setMessage(getString(R.string.loading));
225 progress.setCancelable(false); 234 progress.setCancelable(false);
226 progress.show(); 235 progress.show();
227 ApiServices.topInfo(date, stepType, new LLAPIManagerListener() { 236 ApiServices.topInfo(date, stepType, new LLAPIManagerListener() {
228 @Override 237 @Override
229 public void onError(Error error) { 238 public void onError(Error error) {
230 Debug.error("Get data history error"); 239 Debug.error("Get data history error");
231 hiddenDialog(); 240 hiddenDialog();
232 showDialogNotData(); 241 showDialogNotData();
233 } 242 }
234 243
235 @Override 244 @Override
236 public void onSuccess(String json) { 245 public void onSuccess(String json) {
237 Debug.error("Get data history success"); 246 Debug.error("Get data history success");
238 loadDataDone(json); 247 loadDataDone(json);
239 } 248 }
240 249
241 @Override 250 @Override
242 public void onSuccess(JSONObject object) { 251 public void onSuccess(JSONObject object) {
243 Debug.error("Get data history success"); 252 Debug.error("Get data history success");
244 hiddenDialog(); 253 hiddenDialog();
245 } 254 }
246 }); 255 });
247 } 256 }
248 257
249 private void showDialogNotData(){ 258 private void showDialogNotData(){
250 showAlerDialog(mContext, getResources().getString(R.string.can_not_get_data)); 259 showAlerDialog(mContext, getResources().getString(R.string.can_not_get_data));
251 } 260 }
252 261
253 private void loadDataDone(String jsonString) { 262 private void loadDataDone(String jsonString) {
254 JSONObject jsonObject = null; 263 JSONObject jsonObject = null;
255 try { 264 try {
256 jsonObject = new JSONObject(jsonString); 265 jsonObject = new JSONObject(jsonString);
257 int status = jsonObject.optInt("status"); 266 int status = jsonObject.optInt("status");
258 if (status == 1) { 267 if (status == 1) {
259 JSONObject jsonObject1 = jsonObject.optJSONObject("result"); 268 JSONObject jsonObject1 = jsonObject.optJSONObject("result");
260 JSONObject targetInf = jsonObject1.getJSONObject("targetInf"); 269 JSONObject targetInf = jsonObject1.getJSONObject("targetInf");
261 270
262 if (targetInf != null){ 271 if (targetInf != null){
263 String target = targetInf.optString("target_step"); 272 String target = targetInf.optString("target_step");
264 Debug.normal("Target: "+ target); 273 Debug.normal("Target: "+ target);
265 mTopInfo.setTaget(targetInf.optString("target_step")); 274 mTopInfo.setTaget(targetInf.optString("target_step"));
266 mTopInfo.setSteps(targetInf.optString("num_step")); 275 mTopInfo.setSteps(targetInf.optString("num_step"));
267 mTopInfo.setStepRemain(targetInf.optString("remaining_step")); 276 mTopInfo.setStepRemain(targetInf.optString("remaining_step"));
268 mTopInfo.setCompletePercent(targetInf.optString("complete_percent")); 277 mTopInfo.setCompletePercent(targetInf.optString("complete_percent"));
269 } 278 }
270 279
271 mTopInfo.setKcalo(jsonObject1.optString("kcal")); 280 mTopInfo.setKcalo(jsonObject1.optString("kcal"));
272 mTopInfo.setDistance(jsonObject1.optString("distance")); 281 mTopInfo.setDistance(jsonObject1.optString("distance"));
273 mTopInfo.setTime(jsonObject1.optString("time")); 282 mTopInfo.setTime(jsonObject1.optString("time"));
274 JSONArray stepArr = jsonObject1.optJSONArray("dataChart"); 283 JSONArray stepArr = jsonObject1.optJSONArray("dataChart");
275 284
276 285
277 if (stepArr != null && stepArr.length() > 0) { 286 if (stepArr != null && stepArr.length() > 0) {
278 List<StepItemInfo> infoLists = new ArrayList<>(); 287 List<StepItemInfo> infoLists = new ArrayList<>();
279 for (int i = 0; i < stepArr.length(); i++){ 288 for (int i = 0; i < stepArr.length(); i++){
280 StepItemInfo stepItemInfo = new StepItemInfo(); 289 StepItemInfo stepItemInfo = new StepItemInfo();
281 JSONObject ob = (JSONObject) stepArr.get(i); 290 JSONObject ob = (JSONObject) stepArr.get(i);
282 stepItemInfo.setHour(ob.optInt("hour")); 291 stepItemInfo.setHour(ob.optInt("hour"));
283 stepItemInfo.setNumStep(ob.optInt("numStep")); 292 stepItemInfo.setNumStep(ob.optInt("numStep"));
284 infoLists.add(stepItemInfo); 293 infoLists.add(stepItemInfo);
285 } 294 }
286 295
287 mTopInfo.setStepList(infoLists); 296 mTopInfo.setStepList(infoLists);
288 } 297 }
289 298
290 } 299 }
291 } catch (JSONException e) { 300 } catch (JSONException e) {
292 e.printStackTrace(); 301 e.printStackTrace();
293 mTopInfo = new TopInfo();; 302 mTopInfo = new TopInfo();;
294 } 303 }
295 304
296 stepsDistanceChanged(); 305 stepsDistanceChanged();
297 } 306 }
298 307
299 private void updatePie() { 308 private void updatePie() {
300 // todayOffset might still be Integer.MIN_VALUE on first start 309 // todayOffset might still be Integer.MIN_VALUE on first start
301 int stepsToday = 0; 310 int stepsToday = 0;
302 int stepTarget = 0; 311 int stepTarget = 0;
303 if (mTopInfo != null) { 312 if (mTopInfo != null) {
304 if (mTopInfo.getSteps().contains(",")){ 313 if (mTopInfo.getSteps().contains(",")){
305 stepsToday = Integer.valueOf(mTopInfo.getSteps().replace(",", "")); 314 stepsToday = Integer.valueOf(mTopInfo.getSteps().replace(",", ""));
306 }else { 315 }else {
307 stepsToday = Integer.valueOf(mTopInfo.getSteps()); 316 stepsToday = Integer.valueOf(mTopInfo.getSteps());
308 } 317 }
309 318
310 if (mTopInfo.getTaget().contains(",")) { 319 if (mTopInfo.getTaget().contains(",")) {
311 stepTarget = Integer.valueOf(mTopInfo.getTaget().replace(",", "")); 320 stepTarget = Integer.valueOf(mTopInfo.getTaget().replace(",", ""));
312 }else { 321 }else {
313 stepTarget = Integer.valueOf(mTopInfo.getTaget()); 322 stepTarget = Integer.valueOf(mTopInfo.getTaget());
314 } 323 }
315 } 324 }
316 sliceCurrent.setValue(stepsToday); 325 sliceCurrent.setValue(stepsToday);
317 if (stepTarget - stepsToday > 0) { 326 if (stepTarget - stepsToday > 0) {
318 // goal not reached yet 327 // goal not reached yet
319 if (pg.getData().size() == 1) { 328 if (pg.getData().size() == 1) {
320 pg.addPieSlice(sliceGoal); 329 pg.addPieSlice(sliceGoal);
321 } 330 }
322 sliceGoal.setValue(stepTarget - stepsToday); 331 sliceGoal.setValue(stepTarget - stepsToday);
323 } else { 332 } else {
324 // goal reached 333 // goal reached
325 pg.clearChart(); 334 pg.clearChart();
326 pg.addPieSlice(sliceCurrent); 335 pg.addPieSlice(sliceCurrent);
327 } 336 }
328 pg.update(); 337 pg.update();
329 stepGoal = stepTarget; 338 stepGoal = stepTarget;
330 stepTotal = stepsToday; 339 stepTotal = stepsToday;
331 stepsView.setText(formatter.format(stepsToday)); 340 stepsView.setText(formatter.format(stepsToday));
332 int stepRemain = stepTarget - stepsToday; 341 int stepRemain = stepTarget - stepsToday;
333 tvStepRemain.setText(String.valueOf(stepRemain)); 342 tvStepRemain.setText(String.valueOf(stepRemain));
334 tvStepRateDone.setText(getResources().getString(R.string.percent_unit, Utils.convert2String2Decimal(stepsToday *100/ stepTarget))); 343 tvStepRateDone.setText(getResources().getString(R.string.percent_unit, Utils.convert2String2Decimal(stepsToday *100/ stepTarget)));
335 tvSmallRemain.setText(getResources().getString(R.string.pie_text_content3a, stepRemain)); 344 tvSmallRemain.setText(getResources().getString(R.string.pie_text_content3a, stepRemain));
336 tvStepGoal.setText(mTopInfo.getTaget()); 345 tvStepGoal.setText(mTopInfo.getTaget());
337 tvSmallStepGoal.setText(mTopInfo.getTaget()); 346 tvSmallStepGoal.setText(mTopInfo.getTaget());
338 347
339 tvDistance.setText(mTopInfo.getDistance()); 348 tvDistance.setText(mTopInfo.getDistance());
340 tvTime.setText(mTopInfo.getTime()); 349 tvTime.setText(mTopInfo.getTime());
341 350
342 double distanceToday = stepsToday * STEP_SIZE; 351 double distanceToday = stepsToday * STEP_SIZE;
343 distanceToday /= 100000; 352 distanceToday /= 100000;
344 tvDistance.setText(Utils.convert2String2Decimal(distanceToday)); 353 tvDistance.setText(Utils.convert2String2Decimal(distanceToday));
345 354
346 } 355 }
347 356
348 /** 357 /**
349 * Updates the bar graph to show the steps/distance of the last week. Should 358 * Updates the bar graph to show the steps/distance of the last week. Should
350 * be called when switching from step count to distance. 359 * be called when switching from step count to distance.
351 */ 360 */
352 private void updateBars() { 361 private void updateBars() {
353 362
354 dateList = new ArrayList<>(); 363 dateList = new ArrayList<>();
355 List<String> dateList = new ArrayList<>(); 364 List<String> dateList = new ArrayList<>();
356 List<Integer> stepList = new ArrayList<>(); 365 List<Integer> stepList = new ArrayList<>();
357 List<StepItemInfo> stepItemInfos = mTopInfo.getStepList(); 366 List<StepItemInfo> stepItemInfos = mTopInfo.getStepList();
358 if (stepItemInfos != null && stepItemInfos.size() >0) { 367 if (stepItemInfos != null && stepItemInfos.size() >0) {
359 for (int i = 0; i < stepItemInfos.size(); i++){ 368 for (int i = 0; i < stepItemInfos.size(); i++){
360 dateList.add(String.valueOf(stepItemInfos.get(i).getHour())); 369 dateList.add(String.valueOf(stepItemInfos.get(i).getHour()));
361 stepList.add(stepItemInfos.get(i).getNumStep()); 370 stepList.add(stepItemInfos.get(i).getNumStep());
362 } 371 }
363 } 372 }
364 373
365 mStep = stepList.toArray(new Integer[0]); 374 mStep = stepList.toArray(new Integer[0]);
366 mParties = dateList.toArray(new String[0]); 375 mParties = dateList.toArray(new String[0]);
367 376
368 initGraph(); 377 initGraph();
369 } 378 }
370 379
371 private void initGraph(){ 380 private void initGraph(){
372 381
373 mChart.setDrawBarShadow(false); 382 mChart.setDrawBarShadow(false);
374 mChart.setDrawValueAboveBar(true); 383 mChart.setDrawValueAboveBar(true);
375 384
376 // if more than 60 entries are displayed in the chart, no values will be 385 // if more than 60 entries are displayed in the chart, no values will be
377 // drawn 386 // drawn
378 mChart.setMaxVisibleValueCount(60); 387 mChart.setMaxVisibleValueCount(60);
379 388
380 mChart.getDescription().setEnabled(false); 389 mChart.getDescription().setEnabled(false);
381 // scaling can now only be done on x- and y-axis separately 390 // scaling can now only be done on x- and y-axis separately
382 mChart.setPinchZoom(false); 391 mChart.setPinchZoom(false);
383 392
384 mChart.setDrawGridBackground(false); 393 mChart.setDrawGridBackground(false);
385 // mChart.setDrawYLabels(false); 394 // mChart.setDrawYLabels(false);
386 List<String> listx = Arrays.asList(mParties); 395 List<String> listx = Arrays.asList(mParties);
387 DayAxisValueFormatter xValueFormatter = new DayAxisValueFormatter(listx); 396 DayAxisValueFormatter xValueFormatter = new DayAxisValueFormatter(listx);
388 397
389 XAxis xAxis = mChart.getXAxis(); 398 XAxis xAxis = mChart.getXAxis();
390 xAxis.setLabelRotationAngle(0); 399 xAxis.setLabelRotationAngle(0);
391 xAxis.setPosition(XAxis.XAxisPosition.TOP); 400 xAxis.setPosition(XAxis.XAxisPosition.TOP);
392 xAxis.setDrawGridLines(true); 401 xAxis.setDrawGridLines(true);
393 xAxis.setLabelCount(10); 402 xAxis.setLabelCount(10);
394 xAxis.setTextColor(Color.WHITE); 403 xAxis.setTextColor(Color.WHITE);
395 xAxis.setValueFormatter(xValueFormatter); 404 xAxis.setValueFormatter(xValueFormatter);
396 405
397 406
398 YAxis leftAxis = mChart.getAxisLeft(); 407 YAxis leftAxis = mChart.getAxisLeft();
399 leftAxis.setDrawLabels(false); 408 leftAxis.setDrawLabels(false);
400 leftAxis.setDrawGridLines(false); 409 leftAxis.setDrawGridLines(false);
401 leftAxis.setAxisMinimum(0f); 410 leftAxis.setAxisMinimum(0f);
402 leftAxis.setAxisMaximum(10000f); 411 leftAxis.setAxisMaximum(10000f);
403 leftAxis.setDrawZeroLine(false); 412 leftAxis.setDrawZeroLine(false);
404 413
405 leftAxis.setEnabled(false); 414 leftAxis.setEnabled(false);
406 mChart.setDrawValueAboveBar(false); 415 mChart.setDrawValueAboveBar(false);
407 mChart.getAxisRight().setEnabled(false); 416 mChart.getAxisRight().setEnabled(false);
408 417
409 // set auto scale min max 418 // set auto scale min max
410 mChart.setAutoScaleMinMaxEnabled(true); 419 mChart.setAutoScaleMinMaxEnabled(true);
411 mChart.notifyDataSetChanged(); 420 mChart.notifyDataSetChanged();
412 421
413 // Set enimate y 422 // Set enimate y
414 mChart.animateY(2000); 423 mChart.animateY(2000);
415 424
416 setData(); 425 setData();
417 426
418 mChart.getLegend().setEnabled(false); 427 mChart.getLegend().setEnabled(false);
419 } 428 }
420 429
421 430
422 private void setData() { 431 private void setData() {
423 432
424 ArrayList<String> xVals = new ArrayList<>(); 433 ArrayList<String> xVals = new ArrayList<>();
425 for (int i = 0; i < mStep.length; i++) { 434 for (int i = 0; i < mStep.length; i++) {
426 xVals.add(mParties[i % mStep.length]); 435 xVals.add(mParties[i % mStep.length]);
427 } 436 }
428 437
429 ArrayList<BarEntry> yVals1 = new ArrayList<>(); 438 ArrayList<BarEntry> yVals1 = new ArrayList<>();
430 for (int i = 0; i < mStep.length; i++) { 439 for (int i = 0; i < mStep.length; i++) {
431 float val = (float) (mStep[i]*1); 440 float val = (float) (mStep[i]*1);
432 yVals1.add(new BarEntry(i, val)); 441 yVals1.add(new BarEntry(i, val));
433 } 442 }
434 443
435 BarDataSet set1; 444 BarDataSet set1;
436 445
437 if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { 446 if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
438 set1 = (BarDataSet)mChart.getData().getDataSetByIndex(0); 447 set1 = (BarDataSet)mChart.getData().getDataSetByIndex(0);
439 set1.setValues(yVals1); 448 set1.setValues(yVals1);
440 mChart.getData().notifyDataChanged(); 449 mChart.getData().notifyDataChanged();
441 mChart.notifyDataSetChanged(); 450 mChart.notifyDataSetChanged();
442 } else { 451 } else {
443 ArrayList<Integer> colors = new ArrayList<>(); 452 ArrayList<Integer> colors = new ArrayList<>();
444 453
445 454
446 int[] MATERIAL_COLORS = {rgb("#40CDEF")}; 455 int[] MATERIAL_COLORS = {rgb("#40CDEF")};
447 456
448 for (int c : MATERIAL_COLORS) 457 for (int c : MATERIAL_COLORS)
449 colors.add(c); 458 colors.add(c);
450 459
451 set1 = new BarDataSet(yVals1, null); 460 set1 = new BarDataSet(yVals1, null);
452 461
453 set1.setColors(colors); 462 set1.setColors(colors);
454 463
455 ArrayList<IBarDataSet> dataSets = new ArrayList<>(); 464 ArrayList<IBarDataSet> dataSets = new ArrayList<>();
456 dataSets.add(set1); 465 dataSets.add(set1);
457 466
458 BarData data = new BarData(dataSets); 467 BarData data = new BarData(dataSets);
459 data.setValueTextSize(10f); 468 data.setValueTextSize(10f);
460 469
461 mChart.setData(data); 470 mChart.setData(data);
462 } 471 }
463 } 472 }
464 473
465 474
466 475
467 private void handleEvent(){ 476 private void handleEvent(){
468 tvDate.setOnClickListener(new View.OnClickListener() { 477 tvDate.setOnClickListener(new View.OnClickListener() {
469 @Override 478 @Override
470 public void onClick(View view) { 479 public void onClick(View view) {
471 handleAnaDatePicker(); 480 handleAnaDatePicker();
472 } 481 }
473 }); 482 });
474 483
475 ivBack.setOnClickListener(new View.OnClickListener() { 484 ivBack.setOnClickListener(new View.OnClickListener() {
476 @Override 485 @Override
477 public void onClick(View view) { 486 public void onClick(View view) {
478 mCalendar = Calendar.getInstance(); 487 mCalendar = Calendar.getInstance();
479 mCalendar.setTime(mAnaDate); 488 mCalendar.setTime(mAnaDate);
480 mCalendar.add(Calendar.DAY_OF_MONTH, -1); 489 mCalendar.add(Calendar.DAY_OF_MONTH, -1);
481 Date date = mCalendar.getTime(); 490 Date date = mCalendar.getTime();
482 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 491 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
483 mAnaDate = date; 492 mAnaDate = date;
493
494 getTopPage(mAnaDate, stepType);
484 } 495 }
485 }); 496 });
486 497
487 ivNext.setOnClickListener(new View.OnClickListener() { 498 ivNext.setOnClickListener(new View.OnClickListener() {
488 @Override 499 @Override
489 public void onClick(View view) { 500 public void onClick(View view) {
490 mCalendar = Calendar.getInstance(); 501 mCalendar = Calendar.getInstance();
491 mCalendar.setTime(mAnaDate); 502 mCalendar.setTime(mAnaDate);
492 mCalendar.add(Calendar.DAY_OF_MONTH, +1); 503 mCalendar.add(Calendar.DAY_OF_MONTH, +1);
493 Date date = mCalendar.getTime(); 504 Date date = mCalendar.getTime();
494 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 505 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
495 mAnaDate = date; 506 mAnaDate = date;
507
508 getTopPage(mAnaDate, stepType);
496 } 509 }
497 }); 510 });
498 511
499 llBike.setOnClickListener(new View.OnClickListener() { 512 llBike.setOnClickListener(new View.OnClickListener() {
500 @Override 513 @Override
501 public void onClick(View view) { 514 public void onClick(View view) {
502 stepType = Const.STEP_TYPE.BIKE; 515 stepType = Const.STEP_TYPE.BIKE;
503 updateUiStepType(true, false, false); 516 updateUiStepType(true, false, false);
504 getTopPage(mAnaDate, stepType); 517 getTopPage(mAnaDate, stepType);
505 } 518 }
506 }); 519 });
507 520
508 llRunning.setOnClickListener(new View.OnClickListener() { 521 llRunning.setOnClickListener(new View.OnClickListener() {
509 @Override 522 @Override
510 public void onClick(View view) { 523 public void onClick(View view) {
511 stepType = Const.STEP_TYPE.RUNNING; 524 stepType = Const.STEP_TYPE.RUNNING;
512 updateUiStepType(false, false, true); 525 updateUiStepType(false, false, true);
513 getTopPage(mAnaDate, stepType); 526 getTopPage(mAnaDate, stepType);
514 } 527 }
515 }); 528 });
516 529
517 llWalking.setOnClickListener(new View.OnClickListener() { 530 llWalking.setOnClickListener(new View.OnClickListener() {
518 @Override 531 @Override
519 public void onClick(View view) { 532 public void onClick(View view) {
520 stepType = Const.STEP_TYPE.WALKING; 533 stepType = Const.STEP_TYPE.WALKING;
521 updateUiStepType(false, true, false); 534 updateUiStepType(false, true, false);
522 getTopPage(mAnaDate, stepType); 535 getTopPage(mAnaDate, stepType);
523 } 536 }
524 }); 537 });
525 538
526 539
527 } 540 }
528 541
529 542
530 /** 543 /**
531 * Show date picker dialog 544 * Show date picker dialog
532 */ 545 */
533 private void handleAnaDatePicker() { 546 private void handleAnaDatePicker() {
534 547
535 new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { 548 new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
536 @Override 549 @Override
537 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 550 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
538 551
539 mCalendar = Calendar.getInstance(); 552 mCalendar = Calendar.getInstance();
540 mCalendar.set(year, monthOfYear, dayOfMonth); 553 mCalendar.set(year, monthOfYear, dayOfMonth);
541 mAnaYear = year; 554 mAnaYear = year;
542 mAnaMonth = monthOfYear; 555 mAnaMonth = monthOfYear;
543 mAnaDay = dayOfMonth; 556 mAnaDay = dayOfMonth;
544 Date date = mCalendar.getTime(); 557 Date date = mCalendar.getTime();
545 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date)); 558 tvDate.setText(Utils.dateToStringFormatDayMonthYearJp(date));
546 mAnaDate = date; 559 mAnaDate = date;
547 getTopPage(mAnaDate, stepType); 560 getTopPage(mAnaDate, stepType);
548 } 561 }
549 }, mAnaYear, mAnaMonth, mAnaDay).show(); 562 }, mAnaYear, mAnaMonth, mAnaDay).show();
550 563
551 } 564 }
552 565
553 566
554 private void updateUI(){ 567 private void updateUI(){
568 creatLogStep();
569
555 Debug.normal("Step total================ "+ stepTotal); 570 Debug.normal("Step total================ "+ stepTotal);
556 int stepRemain = stepGoal - stepTotal; 571 int stepRemain = stepGoal - stepTotal;
557 double percentDone = stepTotal *100.0 / stepGoal; 572 double percentDone = stepTotal *100.0 / stepGoal;
558 stepsView.setText(String.valueOf(stepTotal)); 573 stepsView.setText(String.valueOf(stepTotal));
559 tvStepRemain.setText(String.valueOf(stepRemain)); 574 tvStepRemain.setText(String.valueOf(stepRemain));
560 tvStepRateDone.setText(getResources().getString(R.string.percent_unit, Utils.convert2String2Decimal(percentDone))); 575 tvStepRateDone.setText(getResources().getString(R.string.percent_unit, Utils.convert2String2Decimal(percentDone)));
561 tvSmallRemain.setText(String.valueOf(stepRemain)); 576 tvSmallRemain.setText(String.valueOf(stepRemain));
562 } 577 }
563 578
564 @Override 579 @Override
565 public void onAttach(Context context) { 580 public void onAttach(Context context) {
566 super.onAttach(context); 581 super.onAttach(context);
567 582
568 } 583 }
569 584
570 @Override 585 @Override
571 public void onSaveData() { 586 public void onSaveData() {
572 587
573 } 588 }
574 589
575 @Override 590 @Override
576 public void onInvalidate(boolean isInit) { 591 public void onInvalidate(boolean isInit) {
577 initData(); 592 initData();
578 } 593 }
579 594
580 @Override 595 @Override
581 public void onViewStateRestored(@Nullable Bundle savedInstanceState) { 596 public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
582 super.onViewStateRestored(savedInstanceState); 597 super.onViewStateRestored(savedInstanceState);
583 598
584 initData(); 599 initData();
585 } 600 }
586 601
587 602
588 @Override 603 @Override
589 public void onResume() { 604 public void onResume() {
590 super.onResume(); 605 super.onResume();
591 activityRunning = true; 606 activityRunning = true;
592 Debug.normal("Today: "+ "Onresume "); 607 Debug.normal("Today: "+ "Onresume ");
608
593 Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); 609 Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
594 if (countSensor != null) { 610 if (countSensor == null) {
595 Debug.normal("Today: "+ "countSensor not null "); 611 isAccelo = true;
596 sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI); 612 countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
597 } else {
598 Debug.normal("Today: "+ "countSensor is null ");
599 Toast.makeText(mContext, getResources().getString(R.string.sensor_available), Toast.LENGTH_SHORT).show();
600 } 613 }
614 if (countSensor != null) {
615 Debug.normal("Today: " + "countSensor not null ");
616 sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
617 } else {
618 Debug.normal("Today: " + "countSensor is null ");
619 Toast.makeText(mContext, getResources().getString(R.string.sensor_available), Toast.LENGTH_SHORT).show();
620 }
621
601 } 622 }
602 623
603 @Override 624 @Override
604 public void onSensorChanged(SensorEvent event) { 625 public void onSensorChanged(SensorEvent event) {
605 Debug.normal("Sensor count step active"); 626 //Debug.normal("Sensor count step active");
606 if (activityRunning){ 627 if (activityRunning){
607 stepCount = (int) event.values[0]; 628 if (isAccelo) {
608 Debug.normal("Step change: "+ stepCount); 629 simpleStepDetector.updateAccel(
609 stepTotal++; 630 event.timestamp, event.values[0], event.values[1], event.values[2]);
610 // update UI 631 }else {
611 updateUI(); 632 stepCount = (int) event.values[0];
633 Debug.normal("Step change: " + stepCount);
634 stepTotal++;
635 // update UI
636 updateUI();
637 }
612 } 638 }
613 } 639 }
614 640
615 @Override 641 @Override
616 public void onAccuracyChanged(Sensor sensor, int accuracy) { 642 public void onAccuracyChanged(Sensor sensor, int accuracy) {
617 643
618 } 644 }
619 645
620 @Override 646 @Override
621 public void onPause() { 647 public void onPause() {
622 super.onPause(); 648 super.onPause();
623 activityRunning = false; 649 activityRunning = false;
624 Debug.normal("Start create log"); 650 Debug.normal("Start create log");
625 mToDate = new Date();
626 if (sensorManager != null) { 651 if (sensorManager != null) {
627 sensorManager.unregisterListener(this); 652 sensorManager.unregisterListener(this);
628 } 653 }
629 // create log step 654 // create log step
630 creatLogStep(); 655 //creatLogStep();
631 } 656 }
632 657
633 @Override 658 @Override
634 public void onDestroy() { 659 public void onDestroy() {
635 super.onDestroy(); 660 super.onDestroy();
636 } 661 }
637 662
638 private void creatLogStep(){ 663 private void creatLogStep(){
639 Debug.normal("Today: "+ "Create log "+ stepCount); 664 Debug.normal("Today: "+ "Create log "+ stepCount);
665 mToDate = new Date();
640 666
641 ApiServices.createLog(stepType, stepCount, mFromDate, mToDate, new LLAPIManagerListener() { 667 ApiServices.createLog(stepType, stepCount, mFromDate, mToDate, new LLAPIManagerListener() {
642 @Override 668 @Override
643 public void onError(Error error) { 669 public void onError(Error error) {
670 isBusy = false;
644 Debug.error("Get data history error"); 671 Debug.error("Get data history error");
645 } 672 }
646 673
647 @Override 674 @Override
648 public void onSuccess(String json) { 675 public void onSuccess(String json) {
676 isBusy = false;
649 Debug.error("Get data history success"); 677 Debug.error("Get data history success");
650 } 678 }
651 679
652 @Override 680 @Override
653 public void onSuccess(JSONObject object) { 681 public void onSuccess(JSONObject object) {
682 isBusy = false;
654 Debug.error("Get data history success"); 683 Debug.error("Get data history success");
655 } 684 }
656 }); 685 });
657 } 686 }
658 687
659 688
660 689 @Override
690 public void step(long timeNs) {
691 if (!isBusy) {
692 isBusy = true;
693 stepCount = 1;
694 stepTotal++;
695 // update UI
696 updateUI();
app/src/main/java/com/dinhcv/lifelogpedometer/interfaces/StepListener.java
File was created 1 package com.dinhcv.lifelogpedometer.interfaces;
2
3 /**
4 * Created by Administrator on 08/01/2018.
5 */
6
7 public interface StepListener {
8 public void step(long timeNs);
9 }
10
app/src/main/java/com/dinhcv/lifelogpedometer/portal/LLAPIManager.java
1 package com.dinhcv.lifelogpedometer.portal; 1 package com.dinhcv.lifelogpedometer.portal;
2 2
3 import android.content.Context; 3 import android.content.Context;
4 import android.content.res.AssetManager; 4 import android.content.res.AssetManager;
5 import android.graphics.Bitmap; 5 import android.graphics.Bitmap;
6 import android.graphics.BitmapFactory; 6 import android.graphics.BitmapFactory;
7 import android.os.AsyncTask; 7 import android.os.AsyncTask;
8 import android.os.Environment; 8 import android.os.Environment;
9 import android.util.Base64; 9 import android.util.Base64;
10 import android.util.Log; 10 import android.util.Log;
11 11
12 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener; 12 import com.dinhcv.lifelogpedometer.interfaces.LLAPIManagerListener;
13 import com.dinhcv.lifelogpedometer.model.Shareprefer.Setting; 13 import com.dinhcv.lifelogpedometer.model.Shareprefer.Setting;
14 import com.dinhcv.lifelogpedometer.model.structure.RegisterInfo; 14 import com.dinhcv.lifelogpedometer.model.structure.RegisterInfo;
15 import com.dinhcv.lifelogpedometer.utils.Const; 15 import com.dinhcv.lifelogpedometer.utils.Const;
16 import com.dinhcv.lifelogpedometer.utils.Debug; 16 import com.dinhcv.lifelogpedometer.utils.Debug;
17 import com.dinhcv.lifelogpedometer.utils.Utils; 17 import com.dinhcv.lifelogpedometer.utils.Utils;
18 18
19 import org.json.JSONArray; 19 import org.json.JSONArray;
20 import org.json.JSONException; 20 import org.json.JSONException;
21 import org.json.JSONObject; 21 import org.json.JSONObject;
22 22
23 import java.io.ByteArrayOutputStream; 23 import java.io.ByteArrayOutputStream;
24 import java.io.File; 24 import java.io.File;
25 import java.io.FileOutputStream; 25 import java.io.FileOutputStream;
26 import java.io.IOException; 26 import java.io.IOException;
27 import java.io.InputStream; 27 import java.io.InputStream;
28 import java.io.OutputStreamWriter; 28 import java.io.OutputStreamWriter;
29 import java.io.UnsupportedEncodingException; 29 import java.io.UnsupportedEncodingException;
30 import java.net.URLEncoder; 30 import java.net.URLEncoder;
31 import java.util.Date; 31 import java.util.Date;
32 import java.util.HashMap; 32 import java.util.HashMap;
33 import java.util.Map; 33 import java.util.Map;
34 import java.util.concurrent.TimeUnit; 34 import java.util.concurrent.TimeUnit;
35 35
36 import okhttp3.HttpUrl; 36 import okhttp3.HttpUrl;
37 import okhttp3.MediaType; 37 import okhttp3.MediaType;
38 import okhttp3.OkHttpClient; 38 import okhttp3.OkHttpClient;
39 import okhttp3.Request; 39 import okhttp3.Request;
40 import okhttp3.RequestBody; 40 import okhttp3.RequestBody;
41 import okhttp3.Response; 41 import okhttp3.Response;
42 import okhttp3.ResponseBody; 42 import okhttp3.ResponseBody;
43 43
44 public class LLAPIManager { 44 public class LLAPIManager {
45 private static String URL_ROOT = "http://clover.timesfun.jp:9001/"; 45 private static String URL_ROOT = "http://clover.timesfun.jp:9001/";
46 //login info 46 //login info
47 private static String URL_LOGIN_INFO = "login"; 47 private static String URL_LOGIN_INFO = "login";
48 //register info 48 //register info
49 private static String URL_REGISTER_INFO = "register"; 49 private static String URL_REGISTER_INFO = "register";
50 //upload image info 50 //upload image info
51 private static String URL_UPLOAD_IMAGE_INFO = "upload-image"; 51 private static String URL_UPLOAD_IMAGE_INFO = "upload-image";
52 //Search zipcode 52 //Search zipcode
53 private static String URL_FORGET_PASS_INFO = "forgetPass"; 53 private static String URL_FORGET_PASS_INFO = "forgetPass";
54 //history 54 //history
55 private static String URL_HISTORE_INFO = "api/history"; 55 private static String URL_HISTORE_INFO = "api/history";
56 //history detail 56 //history detail
57 private static String URL_HISTORE_DETAIL_INFO = "api/history/detail"; 57 private static String URL_HISTORE_DETAIL_INFO = "api/history/detail";
58 // home 58 // home
59 private static String URL_HOME_INFO = "api/home"; 59 private static String URL_HOME_INFO = "api/home";
60 //Search zipcode 60 //Search zipcode
61 private static String URL_FORGET_PASS_CONFIRM_INFO = "forgetPass/confirm"; 61 private static String URL_FORGET_PASS_CONFIRM_INFO = "forgetPass/confirm";
62 // Refesh Token 62 // Refesh Token
63 private static String URL_REFESH_TOKEN_INFO = "refreshToken"; 63 private static String URL_REFESH_TOKEN_INFO = "refreshToken";
64 // Top info 64 // Top info
65 private static String URL_TOP_INFO = "api/top"; 65 private static String URL_TOP_INFO = "api/top";
66 // Refesh Token 66 // Refesh Token
67 private static String URL_CREATE_LOG_INFO = "api/createLog"; 67 private static String URL_CREATE_LOG_INFO = "api/createLog";
68 // Get news 68 // Get news
69 private static String URL_GET_NEWS_INFO = "api/getnoticesbydate"; 69 private static String URL_GET_NEWS_INFO = "api/getnoticesbydate";
70 70
71 71
72 private static int deviationValue = 1; 72 private static int deviationValue = 1;
73 73
74 public static class Login extends AsyncTask<Void, Void, String>{ 74 public static class Login extends AsyncTask<Void, Void, String>{
75 private Context context; 75 private Context context;
76 private String email; 76 private String email;
77 private String pass; 77 private String pass;
78 private LLAPIManagerListener action; 78 private LLAPIManagerListener action;
79 79
80 public Login(Context context, String email, String pass, LLAPIManagerListener action) { 80 public Login(Context context, String email, String pass, LLAPIManagerListener action) {
81 this.context = context; 81 this.context = context;
82 this.email = email; 82 this.email = email;
83 this.pass = pass; 83 this.pass = pass;
84 this.action = action; 84 this.action = action;
85 } 85 }
86 86
87 @Override 87 @Override
88 protected void onPreExecute() { 88 protected void onPreExecute() {
89 super.onPreExecute(); 89 super.onPreExecute();
90 } 90 }
91 91
92 @Override 92 @Override
93 protected String doInBackground(Void... voids) { 93 protected String doInBackground(Void... voids) {
94 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_LOGIN_INFO); 94 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_LOGIN_INFO);
95 JSONObject jsonObject = new JSONObject(); 95 JSONObject jsonObject = new JSONObject();
96 96
97 try { 97 try {
98 jsonObject.put("email", email); 98 jsonObject.put("email", email);
99 jsonObject.put("password", pass); 99 jsonObject.put("password", pass);
100 100
101 Debug.warn("Json data: " + jsonObject.toString()); 101 Debug.warn("Json data: " + jsonObject.toString());
102 } catch (JSONException e) { 102 } catch (JSONException e) {
103 Debug.normal("Error ", e.getMessage()); 103 Debug.normal("Error ", e.getMessage());
104 } 104 }
105 105
106 MediaType JSON 106 MediaType JSON
107 = MediaType.parse("application/json"); 107 = MediaType.parse("application/json");
108 Debug.normal("JSON STRING: %s", jsonObject.toString()); 108 Debug.normal("JSON STRING: %s", jsonObject.toString());
109 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 109 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
110 110
111 final Request.Builder request = new Request.Builder() 111 final Request.Builder request = new Request.Builder()
112 .url(baseUrl) 112 .url(baseUrl)
113 .header("User-Agent", Utils.getCustomUA()) 113 .header("User-Agent", Utils.getCustomUA())
114 .header("Content-Type", "application/json") 114 .header("Content-Type", "application/json")
115 .post(requestBody); 115 .post(requestBody);
116 116
117 OkHttpClient httpClient = new OkHttpClient.Builder() 117 OkHttpClient httpClient = new OkHttpClient.Builder()
118 .readTimeout(30, TimeUnit.SECONDS) 118 .readTimeout(30, TimeUnit.SECONDS)
119 .writeTimeout(30, TimeUnit.SECONDS) 119 .writeTimeout(30, TimeUnit.SECONDS)
120 .connectTimeout(30, TimeUnit.SECONDS) 120 .connectTimeout(30, TimeUnit.SECONDS)
121 .build(); 121 .build();
122 122
123 String jsonString = null; 123 String jsonString = null;
124 try { 124 try {
125 Response response = httpClient.newCall(request.build()).execute(); 125 Response response = httpClient.newCall(request.build()).execute();
126 if (response == null) { 126 if (response == null) {
127 action.onError(null); 127 action.onError(null);
128 Debug.error("Response is null"); 128 Debug.error("Response is null");
129 return null; 129 return null;
130 } 130 }
131 jsonString = getResponseData(response.body()); 131 jsonString = getResponseData(response.body());
132 132
133 } catch (IOException e) { 133 } catch (IOException e) {
134 Debug.normal("Error %s", e.getMessage()); 134 Debug.normal("Error %s", e.getMessage());
135 } 135 }
136 return jsonString; 136 return jsonString;
137 } 137 }
138 138
139 @Override 139 @Override
140 protected void onCancelled() { 140 protected void onCancelled() {
141 super.onCancelled(); 141 super.onCancelled();
142 action.onError(null); 142 action.onError(null);
143 } 143 }
144 144
145 @Override 145 @Override
146 protected void onPostExecute(String jsonString) { 146 protected void onPostExecute(String jsonString) {
147 super.onPostExecute(jsonString); 147 super.onPostExecute(jsonString);
148 148
149 if ((jsonString == null) || (jsonString.isEmpty())) { 149 if ((jsonString == null) || (jsonString.isEmpty())) {
150 action.onError(null); 150 action.onError(null);
151 return; 151 return;
152 } 152 }
153 Debug.normal("String body: "+jsonString); 153 Debug.normal("String body: "+jsonString);
154 154
155 try { 155 try {
156 JSONObject jsonObject = new JSONObject(jsonString); 156 JSONObject jsonObject = new JSONObject(jsonString);
157 int status = jsonObject.optInt("status"); 157 int status = jsonObject.optInt("status");
158 if (status == 1){ 158 if (status == 1){
159 JSONObject object = jsonObject.optJSONObject("result"); 159 JSONObject object = jsonObject.optJSONObject("result");
160 JSONObject objUser = object.getJSONObject("user"); 160 JSONObject objUser = object.getJSONObject("user");
161 String token = object.optString("token"); 161 String token = object.optString("token");
162 // save data 162 // save data
163 Setting.setUserDataSharepre(context, Setting.TOKEN_SHAREPRE, token); 163 Setting.setUserDataSharepre(context, Setting.TOKEN_SHAREPRE, token);
164 APIResponse.getInstance().setToken(token); 164 APIResponse.getInstance().setToken(token);
165 Debug.normal("Token: "+ token); 165 Debug.normal("Token: "+ token);
166 action.onSuccess(objUser); 166 action.onSuccess(objUser);
167 }else { 167 }else {
168 action.onError(new Error(jsonObject.optString("message"))); 168 action.onError(new Error(jsonObject.optString("message")));
169 } 169 }
170 } catch (JSONException e) { 170 } catch (JSONException e) {
171 e.printStackTrace(); 171 e.printStackTrace();
172 } 172 }
173 } 173 }
174 } 174 }
175 175
176 public static class UploadImage extends AsyncTask<Void, Void, String>{ 176 public static class UploadImage extends AsyncTask<Void, Void, String>{
177 private Bitmap bitmap; 177 private Bitmap bitmap;
178 private LLAPIManagerListener action; 178 private LLAPIManagerListener action;
179 179
180 public UploadImage(Bitmap bitmap, LLAPIManagerListener action) { 180 public UploadImage(Bitmap bitmap, LLAPIManagerListener action) {
181 this.bitmap = bitmap; 181 this.bitmap = bitmap;
182 this.action = action; 182 this.action = action;
183 } 183 }
184 184
185 @Override 185 @Override
186 protected void onPreExecute() { 186 protected void onPreExecute() {
187 super.onPreExecute(); 187 super.onPreExecute();
188 } 188 }
189 189
190 @Override 190 @Override
191 protected String doInBackground(Void... voids) { 191 protected String doInBackground(Void... voids) {
192 String baseUrl = URL_ROOT + URL_UPLOAD_IMAGE_INFO; 192 String baseUrl = URL_ROOT + URL_UPLOAD_IMAGE_INFO;
193 193
194 Bitmap b = Bitmap.createScaledBitmap(bitmap, 120, 120, false); 194 Bitmap b = Bitmap.createScaledBitmap(bitmap, 120, 120, false);
195 byte[] bitmapByte = convertBitmapToByteArray(b); 195 byte[] bitmapByte = convertBitmapToByteArray(b);
196 String imageBase64 = Base64.encodeToString(bitmapByte, Base64.DEFAULT); 196 String imageBase64 = Base64.encodeToString(bitmapByte, Base64.DEFAULT);
197 197
198 String token = APIResponse.getInstance().getToken(); 198 String token = APIResponse.getInstance().getToken();
199 //generate hashMap to store encodedImage and the name 199 //generate hashMap to store encodedImage and the name
200 HashMap<String,String> detail = new HashMap<>(); 200 HashMap<String,String> detail = new HashMap<>();
201 detail.put("img", imageBase64); 201 detail.put("img", imageBase64);
202 if (token != null && !token.isEmpty()) { 202 if (token != null && !token.isEmpty()) {
203 Debug.normal("Token is not null"); 203 Debug.normal("Token is not null");
204 detail.put("token", token); 204 detail.put("token", token);
205 } 205 }
206 206
207 try { 207 try {
208 String dataToSend = hashMapToUrl(detail); 208 String dataToSend = hashMapToUrl(detail);
209 209
210 String response = RequestPostImage.post(baseUrl,dataToSend); 210 String response = RequestPostImage.post(baseUrl,dataToSend);
211 if (response == null) { 211 if (response == null) {
212 action.onError(null); 212 action.onError(null);
213 Debug.error("Response is null"); 213 Debug.error("Response is null");
214 return null; 214 return null;
215 } 215 }
216 216
217 Debug.normal("Response: "+response); 217 Debug.normal("Response: "+response);
218 return response; 218 return response;
219 } catch (IOException e) { 219 } catch (IOException e) {
220 Debug.normal("Error %s", e.getMessage()); 220 Debug.normal("Error %s", e.getMessage());
221 return null; 221 return null;
222 } 222 }
223 } 223 }
224 224
225 @Override 225 @Override
226 protected void onCancelled() { 226 protected void onCancelled() {
227 super.onCancelled(); 227 super.onCancelled();
228 action.onError(null); 228 action.onError(null);
229 } 229 }
230 230
231 @Override 231 @Override
232 protected void onPostExecute(String jsonString) { 232 protected void onPostExecute(String jsonString) {
233 super.onPostExecute(jsonString); 233 super.onPostExecute(jsonString);
234 if ((jsonString == null) || (jsonString.isEmpty())) { 234 if ((jsonString == null) || (jsonString.isEmpty())) {
235 action.onError(null); 235 action.onError(null);
236 return; 236 return;
237 } 237 }
238 Debug.normal("String body: "+jsonString); 238 Debug.normal("String body: "+jsonString);
239 239
240 try { 240 try {
241 JSONObject jsonObject = new JSONObject(jsonString); 241 JSONObject jsonObject = new JSONObject(jsonString);
242 int status = jsonObject.optInt("httpCode"); 242 int status = jsonObject.optInt("httpCode");
243 if (status != 0){ 243 if (status != 0){
244 action.onSuccess(jsonObject.optString("message")); 244 action.onSuccess(jsonObject.optString("message"));
245 }else { 245 }else {
246 action.onError(new Error(jsonObject.optString("message"))); 246 action.onError(new Error(jsonObject.optString("message")));
247 } 247 }
248 } catch (JSONException e) { 248 } catch (JSONException e) {
249 e.printStackTrace(); 249 e.printStackTrace();
250 } 250 }
251 } 251 }
252 } 252 }
253 253
254 public static class UploadImage1 extends AsyncTask<Void, Void, String>{ 254 public static class UploadImage1 extends AsyncTask<Void, Void, String>{
255 private Bitmap bitmap; 255 private Bitmap bitmap;
256 private LLAPIManagerListener action; 256 private LLAPIManagerListener action;
257 257
258 public UploadImage1(Bitmap bitmap, LLAPIManagerListener action) { 258 public UploadImage1(Bitmap bitmap, LLAPIManagerListener action) {
259 this.bitmap = bitmap; 259 this.bitmap = bitmap;
260 this.action = action; 260 this.action = action;
261 } 261 }
262 262
263 @Override 263 @Override
264 protected void onPreExecute() { 264 protected void onPreExecute() {
265 super.onPreExecute(); 265 super.onPreExecute();
266 } 266 }
267 267
268 @Override 268 @Override
269 protected String doInBackground(Void... voids) { 269 protected String doInBackground(Void... voids) {
270 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_UPLOAD_IMAGE_INFO); 270 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_UPLOAD_IMAGE_INFO);
271 JSONObject jsonObject = new JSONObject(); 271 JSONObject jsonObject = new JSONObject();
272 Bitmap b = Bitmap.createScaledBitmap(bitmap, 120, 120, false); 272 Bitmap b = Bitmap.createScaledBitmap(bitmap, 120, 120, false);
273 byte[] bitmapByte = convertBitmapToByteArray(b); 273 byte[] bitmapByte = convertBitmapToByteArray(b);
274 String imageBase64 = Base64.encodeToString(bitmapByte, Base64.DEFAULT); 274 String imageBase64 = Base64.encodeToString(bitmapByte, Base64.DEFAULT);
275 //String imageStr = imageBase64.replace("\n",""); 275 //String imageStr = imageBase64.replace("\n","");
276 //writeToFile(imageBase64); 276 //writeToFile(imageBase64);
277 277
278 String token = APIResponse.getInstance().getToken(); 278 String token = APIResponse.getInstance().getToken();
279 try { 279 try {
280 if (token != null && !token.isEmpty()) { 280 if (token != null && !token.isEmpty()) {
281 Debug.normal("Token is not null"); 281 Debug.normal("Token is not null");
282 jsonObject.put("token", token); 282 jsonObject.put("token", token);
283 } 283 }
284 jsonObject.put("img", imageBase64); 284 jsonObject.put("img", imageBase64);
285 285
286 //Debug.warn("Json data: " + jsonObject.toString()); 286 //Debug.warn("Json data: " + jsonObject.toString());
287 } catch (JSONException e) { 287 } catch (JSONException e) {
288 Debug.normal("Error ", e.getMessage()); 288 Debug.normal("Error ", e.getMessage());
289 } 289 }
290 290
291 MediaType JSON 291 MediaType JSON
292 = MediaType.parse("application/json; charset=utf-8"); 292 = MediaType.parse("application/json; charset=utf-8");
293 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 293 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
294 294
295 final Request.Builder request = new Request.Builder() 295 final Request.Builder request = new Request.Builder()
296 .url(baseUrl) 296 .url(baseUrl)
297 .header("Content-Type", "application/json") 297 .header("Content-Type", "application/json")
298 .post(requestBody); 298 .post(requestBody);
299 299
300 OkHttpClient httpClient = new OkHttpClient.Builder() 300 OkHttpClient httpClient = new OkHttpClient.Builder()
301 .readTimeout(30, TimeUnit.SECONDS) 301 .readTimeout(30, TimeUnit.SECONDS)
302 .writeTimeout(30, TimeUnit.SECONDS) 302 .writeTimeout(30, TimeUnit.SECONDS)
303 .connectTimeout(30, TimeUnit.SECONDS) 303 .connectTimeout(30, TimeUnit.SECONDS)
304 .build(); 304 .build();
305 String jsonString = null; 305 String jsonString = null;
306 try { 306 try {
307 Response response = httpClient.newCall(request.build()).execute(); 307 Response response = httpClient.newCall(request.build()).execute();
308 if (response == null) { 308 if (response == null) {
309 action.onError(null); 309 action.onError(null);
310 Debug.error("Response is null"); 310 Debug.error("Response is null");
311 return null; 311 return null;
312 } 312 }
313 jsonString = getResponseData(response.body()); 313 jsonString = getResponseData(response.body());
314 314
315 } catch (IOException e) { 315 } catch (IOException e) {
316 Debug.normal("Error %s", e.getMessage()); 316 Debug.normal("Error %s", e.getMessage());
317 } 317 }
318 318
319 return jsonString; 319 return jsonString;
320 } 320 }
321 321
322 @Override 322 @Override
323 protected void onCancelled() { 323 protected void onCancelled() {
324 super.onCancelled(); 324 super.onCancelled();
325 action.onError(null); 325 action.onError(null);
326 } 326 }
327 327
328 @Override 328 @Override
329 protected void onPostExecute(String jsonString) { 329 protected void onPostExecute(String jsonString) {
330 super.onPostExecute(jsonString); 330 super.onPostExecute(jsonString);
331 if ((jsonString == null) || (jsonString.isEmpty())) { 331 if ((jsonString == null) || (jsonString.isEmpty())) {
332 action.onError(null); 332 action.onError(null);
333 return; 333 return;
334 } 334 }
335 Debug.normal("String body: "+jsonString); 335 Debug.normal("String body: "+jsonString);
336 336
337 try { 337 try {
338 JSONObject jsonObject = new JSONObject(jsonString); 338 JSONObject jsonObject = new JSONObject(jsonString);
339 int status = jsonObject.optInt("status"); 339 int status = jsonObject.optInt("status");
340 if (status == 1){ 340 if (status == 1){
341 action.onSuccess(new JSONObject()); 341 action.onSuccess(new JSONObject());
342 }else { 342 }else {
343 action.onError(new Error(jsonObject.optString("message"))); 343 action.onError(new Error(jsonObject.optString("message")));
344 } 344 }
345 } catch (JSONException e) { 345 } catch (JSONException e) {
346 e.printStackTrace(); 346 e.printStackTrace();
347 } 347 }
348 } 348 }
349 } 349 }
350 350
351 351
352 public static class Register extends AsyncTask<Void, Void, String>{ 352 public static class Register extends AsyncTask<Void, Void, String>{
353 private RegisterInfo registerInfo; 353 private RegisterInfo registerInfo;
354 private LLAPIManagerListener action; 354 private LLAPIManagerListener action;
355 355
356 public Register(RegisterInfo registerInfo, LLAPIManagerListener action) { 356 public Register(RegisterInfo registerInfo, LLAPIManagerListener action) {
357 this.registerInfo = registerInfo; 357 this.registerInfo = registerInfo;
358 this.action = action; 358 this.action = action;
359 } 359 }
360 360
361 @Override 361 @Override
362 protected void onPreExecute() { 362 protected void onPreExecute() {
363 super.onPreExecute(); 363 super.onPreExecute();
364 } 364 }
365 365
366 @Override 366 @Override
367 protected String doInBackground(Void... voids) { 367 protected String doInBackground(Void... voids) {
368 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_REGISTER_INFO); 368 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_REGISTER_INFO);
369 JSONObject jsonObject = new JSONObject(); 369 JSONObject jsonObject = new JSONObject();
370 370
371 String token = APIResponse.getInstance().getToken(); 371 String token = APIResponse.getInstance().getToken();
372 try { 372 try {
373 jsonObject.put("username", registerInfo.getUsername()); 373 jsonObject.put("username", registerInfo.getUsername());
374 jsonObject.put("password", registerInfo.getPassword()); 374 jsonObject.put("password", registerInfo.getPassword());
375 jsonObject.put("password_confirmation", registerInfo.getPassword()); 375 jsonObject.put("password_confirmation", registerInfo.getPassword());
376 jsonObject.put("full_name", registerInfo.getFullName()); 376 jsonObject.put("full_name", registerInfo.getFullName());
377 jsonObject.put("nickname", registerInfo.getNickname()); 377 jsonObject.put("nickname", registerInfo.getNickname());
378 jsonObject.put("birthday", Utils.dateToStringFormatDayMonthYear(registerInfo.getBirthday())); 378 jsonObject.put("birthday", Utils.dateToStringFormatDayMonthYear(registerInfo.getBirthday()));
379 jsonObject.put("height", ""+registerInfo.getHeight()); 379 jsonObject.put("height", ""+registerInfo.getHeight());
380 jsonObject.put("weight", ""+registerInfo.getWeight()); 380 jsonObject.put("weight", ""+registerInfo.getWeight());
381 jsonObject.put("fat_rate", ""+registerInfo.getFatRate()); 381 jsonObject.put("fat_rate", ""+registerInfo.getFatRate());
382 jsonObject.put("gender", ""+registerInfo.getGender()); 382 jsonObject.put("gender", ""+registerInfo.getGender());
383 jsonObject.put("address", ""+registerInfo.getAddress()); 383 jsonObject.put("address", ""+registerInfo.getAddress());
384 jsonObject.put("desciption", ""+registerInfo.getDescription()); 384 jsonObject.put("desciption", ""+registerInfo.getDescription());
385 jsonObject.put("receive_notification", "0"); 385 jsonObject.put("receive_notification", "0");
386 jsonObject.put("phone", "0123-849-869"); 386 jsonObject.put("phone", "0123-849-869");
387 jsonObject.put("share_data", "0"); 387 jsonObject.put("share_data", "0");
388 jsonObject.put("profile_image", ""+registerInfo.getProfileImage()); 388 jsonObject.put("profile_image", ""+registerInfo.getProfileImage());
389 //jsonObject.put("delete_flag", "0"); 389 //jsonObject.put("delete_flag", "0");
390 jsonObject.put("email", registerInfo.getEmail()); 390 jsonObject.put("email", registerInfo.getEmail());
391 jsonObject.put("physical_activity", "0"); 391 jsonObject.put("physical_activity", "0");
392 jsonObject.put("remember_me", "1"); 392 jsonObject.put("remember_me", "1");
393 393
394 Debug.warn("Json data: " + jsonObject.toString()); 394 Debug.warn("Json data: " + jsonObject.toString());
395 } catch (JSONException e) { 395 } catch (JSONException e) {
396 Debug.normal("Error ", e.getMessage()); 396 Debug.normal("Error ", e.getMessage());
397 } 397 }
398 398
399 MediaType JSON 399 MediaType JSON
400 = MediaType.parse("application/json; charset=utf-8"); 400 = MediaType.parse("application/json; charset=utf-8");
401 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 401 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
402 402
403 final Request.Builder request = new Request.Builder() 403 final Request.Builder request = new Request.Builder()
404 .url(baseUrl) 404 .url(baseUrl)
405 .header("User-Agent", Utils.getCustomUA()) 405 .header("User-Agent", Utils.getCustomUA())
406 .header("Content-Type", "application/json") 406 .header("Content-Type", "application/json")
407 .post(requestBody); 407 .post(requestBody);
408 408
409 OkHttpClient httpClient = new OkHttpClient.Builder() 409 OkHttpClient httpClient = new OkHttpClient.Builder()
410 .readTimeout(30, TimeUnit.SECONDS) 410 .readTimeout(30, TimeUnit.SECONDS)
411 .writeTimeout(30, TimeUnit.SECONDS) 411 .writeTimeout(30, TimeUnit.SECONDS)
412 .connectTimeout(30, TimeUnit.SECONDS) 412 .connectTimeout(30, TimeUnit.SECONDS)
413 .build(); 413 .build();
414 414
415 String jsonString = null; 415 String jsonString = null;
416 try { 416 try {
417 Response response = httpClient.newCall(request.build()).execute(); 417 Response response = httpClient.newCall(request.build()).execute();
418 if (response == null) { 418 if (response == null) {
419 action.onError(null); 419 action.onError(null);
420 Debug.error("Response is null"); 420 Debug.error("Response is null");
421 return null; 421 return null;
422 } 422 }
423 jsonString = getResponseData(response.body()); 423 jsonString = getResponseData(response.body());
424 424
425 } catch (IOException e) { 425 } catch (IOException e) {
426 Debug.normal("Error %s", e.getMessage()); 426 Debug.normal("Error %s", e.getMessage());
427 } 427 }
428 return jsonString; 428 return jsonString;
429 } 429 }
430 430
431 @Override 431 @Override
432 protected void onCancelled() { 432 protected void onCancelled() {
433 super.onCancelled(); 433 super.onCancelled();
434 action.onError(null); 434 action.onError(null);
435 } 435 }
436 436
437 @Override 437 @Override
438 protected void onPostExecute(String jsonString) { 438 protected void onPostExecute(String jsonString) {
439 super.onPostExecute(jsonString); 439 super.onPostExecute(jsonString);
440 if ((jsonString == null) || (jsonString.isEmpty())) { 440 if ((jsonString == null) || (jsonString.isEmpty())) {
441 action.onError(null); 441 action.onError(null);
442 return; 442 return;
443 } 443 }
444 Debug.normal("String body: "+jsonString); 444 Debug.normal("String body: "+jsonString);
445 445
446 try { 446 try {
447 JSONObject jsonObject = new JSONObject(jsonString); 447 JSONObject jsonObject = new JSONObject(jsonString);
448 int status = jsonObject.optInt("status"); 448 int status = jsonObject.optInt("status");
449 if (status == 1){ 449 if (status == 1){
450 JSONObject object = jsonObject.optJSONObject("result"); 450 JSONObject object = jsonObject.optJSONObject("result");
451 JSONObject objUser = object.getJSONObject("user"); 451 JSONObject objUser = object.getJSONObject("user");
452 String token = object.optString("token"); 452 String token = object.optString("token");
453 APIResponse.getInstance().setToken(token); 453 APIResponse.getInstance().setToken(token);
454 Debug.normal("Token: "+ token); 454 Debug.normal("Token: "+ token);
455 action.onSuccess(objUser); 455 action.onSuccess(objUser);
456 }else { 456 }else {
457 action.onError(new Error(jsonObject.optString("message"))); 457 action.onError(new Error(jsonObject.optString("message")));
458 } 458 }
459 } catch (JSONException e) { 459 } catch (JSONException e) {
460 e.printStackTrace(); 460 e.printStackTrace();
461 } 461 }
462 462
463 } 463 }
464 } 464 }
465 465
466 private static byte[] convertBitmapToByteArray(Bitmap bitmap) { 466 private static byte[] convertBitmapToByteArray(Bitmap bitmap) {
467 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 467 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
468 bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); 468 bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
469 byte[] byteArray = byteArrayOutputStream.toByteArray(); 469 byte[] byteArray = byteArrayOutputStream.toByteArray();
470 return byteArray; 470 return byteArray;
471 } 471 }
472 472
473 public static class ForgetPass extends AsyncTask<Void, Void, String>{ 473 public static class ForgetPass extends AsyncTask<Void, Void, String>{
474 private String email; 474 private String email;
475 private LLAPIManagerListener action; 475 private LLAPIManagerListener action;
476 476
477 public ForgetPass(String email, LLAPIManagerListener action) { 477 public ForgetPass(String email, LLAPIManagerListener action) {
478 this.email = email; 478 this.email = email;
479 this.action = action; 479 this.action = action;
480 } 480 }
481 481
482 @Override 482 @Override
483 protected void onPreExecute() { 483 protected void onPreExecute() {
484 super.onPreExecute(); 484 super.onPreExecute();
485 } 485 }
486 486
487 @Override 487 @Override
488 protected String doInBackground(Void... voids) { 488 protected String doInBackground(Void... voids) {
489 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_FORGET_PASS_INFO); 489 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_FORGET_PASS_INFO);
490 JSONObject jsonObject = new JSONObject(); 490 JSONObject jsonObject = new JSONObject();
491 try { 491 try {
492 //Personal info 492 //Personal info
493 jsonObject.put("email", email); 493 jsonObject.put("email", email);
494 494
495 Debug.warn("Json data: " + jsonObject.toString()); 495 Debug.warn("Json data: " + jsonObject.toString());
496 } catch (JSONException e) { 496 } catch (JSONException e) {
497 Debug.normal("Error ", e.getMessage()); 497 Debug.normal("Error ", e.getMessage());
498 } 498 }
499 499
500 MediaType JSON 500 MediaType JSON
501 = MediaType.parse("application/json"); 501 = MediaType.parse("application/json");
502 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 502 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
503 503
504 final Request.Builder request = new Request.Builder() 504 final Request.Builder request = new Request.Builder()
505 .url(baseUrl) 505 .url(baseUrl)
506 .header("User-Agent", Utils.getCustomUA()) 506 .header("User-Agent", Utils.getCustomUA())
507 .header("Content-Type", "application/json") 507 .header("Content-Type", "application/json")
508 .post(requestBody); 508 .post(requestBody);
509 509
510 OkHttpClient httpClient = new OkHttpClient.Builder() 510 OkHttpClient httpClient = new OkHttpClient.Builder()
511 .readTimeout(30, TimeUnit.SECONDS) 511 .readTimeout(30, TimeUnit.SECONDS)
512 .writeTimeout(30, TimeUnit.SECONDS) 512 .writeTimeout(30, TimeUnit.SECONDS)
513 .connectTimeout(30, TimeUnit.SECONDS) 513 .connectTimeout(30, TimeUnit.SECONDS)
514 .build(); 514 .build();
515 515
516 String jsonString = null; 516 String jsonString = null;
517 try { 517 try {
518 Response response = httpClient.newCall(request.build()).execute(); 518 Response response = httpClient.newCall(request.build()).execute();
519 if (response == null) { 519 if (response == null) {
520 action.onError(null); 520 action.onError(null);
521 Debug.error("Response is null"); 521 Debug.error("Response is null");
522 return null; 522 return null;
523 } 523 }
524 jsonString = getResponseData(response.body()); 524 jsonString = getResponseData(response.body());
525 525
526 } catch (IOException e) { 526 } catch (IOException e) {
527 Debug.normal("Error %s", e.getMessage()); 527 Debug.normal("Error %s", e.getMessage());
528 } 528 }
529 return jsonString; 529 return jsonString;
530 } 530 }
531 531
532 @Override 532 @Override
533 protected void onCancelled() { 533 protected void onCancelled() {
534 super.onCancelled(); 534 super.onCancelled();
535 action.onError(null); 535 action.onError(null);
536 } 536 }
537 537
538 @Override 538 @Override
539 protected void onPostExecute(String jsonString) { 539 protected void onPostExecute(String jsonString) {
540 super.onPostExecute(jsonString); 540 super.onPostExecute(jsonString);
541 if ((jsonString == null) || (jsonString.isEmpty())) { 541 if ((jsonString == null) || (jsonString.isEmpty())) {
542 action.onError(null); 542 action.onError(null);
543 return; 543 return;
544 } 544 }
545 Debug.normal("String body: "+jsonString); 545 Debug.normal("String body: "+jsonString);
546 546
547 try { 547 try {
548 JSONObject jsonObject = new JSONObject(jsonString); 548 JSONObject jsonObject = new JSONObject(jsonString);
549 int status = jsonObject.optInt("status"); 549 int status = jsonObject.optInt("status");
550 if (status == 1) { 550 if (status == 1) {
551 action.onSuccess(jsonString); 551 action.onSuccess(jsonString);
552 } else { 552 } else {
553 action.onError(new Error(jsonObject.getString("message"))); 553 action.onError(new Error(jsonObject.getString("message")));
554 } 554 }
555 } catch (JSONException e) { 555 } catch (JSONException e) {
556 action.onError(null); 556 action.onError(null);
557 } 557 }
558 } 558 }
559 559
560 } 560 }
561 561
562 public static class ForgetPassConfirm extends AsyncTask<Void, Void, String>{ 562 public static class ForgetPassConfirm extends AsyncTask<Void, Void, String>{
563 private String email; 563 private String email;
564 private String codeConfirm; 564 private String codeConfirm;
565 private LLAPIManagerListener action; 565 private LLAPIManagerListener action;
566 566
567 public ForgetPassConfirm(String email, String codeConfirm, LLAPIManagerListener action) { 567 public ForgetPassConfirm(String email, String codeConfirm, LLAPIManagerListener action) {
568 this.email = email; 568 this.email = email;
569 this.codeConfirm = codeConfirm; 569 this.codeConfirm = codeConfirm;
570 this.action = action; 570 this.action = action;
571 } 571 }
572 572
573 @Override 573 @Override
574 protected void onPreExecute() { 574 protected void onPreExecute() {
575 super.onPreExecute(); 575 super.onPreExecute();
576 } 576 }
577 577
578 @Override 578 @Override
579 protected String doInBackground(Void... voids) { 579 protected String doInBackground(Void... voids) {
580 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_FORGET_PASS_CONFIRM_INFO); 580 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_FORGET_PASS_CONFIRM_INFO);
581 JSONObject jsonObject = new JSONObject(); 581 JSONObject jsonObject = new JSONObject();
582 try { 582 try {
583 //Personal info 583 //Personal info
584 jsonObject.put("email", email); 584 jsonObject.put("email", email);
585 jsonObject.put("code_confirm", codeConfirm); 585 jsonObject.put("code_confirm", codeConfirm);
586 586
587 Debug.warn("Json data: " + jsonObject.toString()); 587 Debug.warn("Json data: " + jsonObject.toString());
588 } catch (JSONException e) { 588 } catch (JSONException e) {
589 Debug.normal("Error ", e.getMessage()); 589 Debug.normal("Error ", e.getMessage());
590 } 590 }
591 591
592 MediaType JSON 592 MediaType JSON
593 = MediaType.parse("application/json"); 593 = MediaType.parse("application/json");
594 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 594 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
595 595
596 final Request.Builder request = new Request.Builder() 596 final Request.Builder request = new Request.Builder()
597 .url(baseUrl) 597 .url(baseUrl)
598 .header("User-Agent", Utils.getCustomUA()) 598 .header("User-Agent", Utils.getCustomUA())
599 .header("Content-Type", "application/json") 599 .header("Content-Type", "application/json")
600 .post(requestBody); 600 .post(requestBody);
601 601
602 OkHttpClient httpClient = new OkHttpClient.Builder() 602 OkHttpClient httpClient = new OkHttpClient.Builder()
603 .readTimeout(30, TimeUnit.SECONDS) 603 .readTimeout(30, TimeUnit.SECONDS)
604 .writeTimeout(30, TimeUnit.SECONDS) 604 .writeTimeout(30, TimeUnit.SECONDS)
605 .connectTimeout(30, TimeUnit.SECONDS) 605 .connectTimeout(30, TimeUnit.SECONDS)
606 .build(); 606 .build();
607 String jsonString = null; 607 String jsonString = null;
608 try { 608 try {
609 Response response = httpClient.newCall(request.build()).execute(); 609 Response response = httpClient.newCall(request.build()).execute();
610 if (response == null) { 610 if (response == null) {
611 action.onError(null); 611 action.onError(null);
612 Debug.error("Response is null"); 612 Debug.error("Response is null");
613 return null; 613 return null;
614 } 614 }
615 jsonString = getResponseData(response.body()); 615 jsonString = getResponseData(response.body());
616 616
617 } catch (IOException e) { 617 } catch (IOException e) {
618 Debug.normal("Error %s", e.getMessage()); 618 Debug.normal("Error %s", e.getMessage());
619 } 619 }
620 return jsonString; 620 return jsonString;
621 } 621 }
622 622
623 @Override 623 @Override
624 protected void onCancelled() { 624 protected void onCancelled() {
625 super.onCancelled(); 625 super.onCancelled();
626 action.onError(null); 626 action.onError(null);
627 } 627 }
628 628
629 @Override 629 @Override
630 protected void onPostExecute(String jsonString) { 630 protected void onPostExecute(String jsonString) {
631 super.onPostExecute(jsonString); 631 super.onPostExecute(jsonString);
632 if ((jsonString == null) || (jsonString.isEmpty())) { 632 if ((jsonString == null) || (jsonString.isEmpty())) {
633 action.onError(null); 633 action.onError(null);
634 return; 634 return;
635 } 635 }
636 Debug.normal("String body: "+jsonString); 636 Debug.normal("String body: "+jsonString);
637 637
638 try { 638 try {
639 JSONObject jsonObject = new JSONObject(jsonString); 639 JSONObject jsonObject = new JSONObject(jsonString);
640 int status = jsonObject.optInt("status"); 640 int status = jsonObject.optInt("status");
641 if (status == 1) { 641 if (status == 1) {
642 action.onSuccess(jsonString); 642 action.onSuccess(jsonString);
643 } else { 643 } else {
644 action.onError(new Error(jsonObject.getString("message"))); 644 action.onError(new Error(jsonObject.getString("message")));
645 } 645 }
646 } catch (JSONException e) { 646 } catch (JSONException e) {
647 action.onError(null); 647 action.onError(null);
648 } 648 }
649 } 649 }
650 } 650 }
651 651
652 public static class History extends AsyncTask<Void, Void, String>{ 652 public static class History extends AsyncTask<Void, Void, String>{
653 private Date fromDate; 653 private Date fromDate;
654 private Date toDate; 654 private Date toDate;
655 private LLAPIManagerListener action; 655 private LLAPIManagerListener action;
656 656
657 public History(Date fromDate, Date toDate, LLAPIManagerListener action) { 657 public History(Date fromDate, Date toDate, LLAPIManagerListener action) {
658 this.fromDate = fromDate; 658 this.fromDate = fromDate;
659 this.toDate = toDate; 659 this.toDate = toDate;
660 this.action = action; 660 this.action = action;
661 } 661 }
662 662
663 @Override 663 @Override
664 protected void onPreExecute() { 664 protected void onPreExecute() {
665 super.onPreExecute(); 665 super.onPreExecute();
666 } 666 }
667 667
668 @Override 668 @Override
669 protected String doInBackground(Void... voids) { 669 protected String doInBackground(Void... voids) {
670 670
671 String fromStr = Utils.dateToStringFormatYearMonthDay(fromDate); 671 String fromStr = Utils.dateToStringFormatYearMonthDay(fromDate);
672 String toStr = Utils.dateToStringFormatYearMonthDay(toDate); 672 String toStr = Utils.dateToStringFormatYearMonthDay(toDate);
673 Debug.normal("Token: "+ APIResponse.getInstance().getToken()); 673 Debug.normal("Token: "+ APIResponse.getInstance().getToken());
674 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_HISTORE_INFO + "/"+ fromStr +"/"+ toStr); 674 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_HISTORE_INFO + "/"+ fromStr +"/"+ toStr);
675 Debug.normal("URL: "+baseUrl.toString()); 675 Debug.normal("URL: "+baseUrl.toString());
676 final Request.Builder request = new Request.Builder() 676 final Request.Builder request = new Request.Builder()
677 .url(baseUrl) 677 .url(baseUrl)
678 .header("User-Agent", Utils.getCustomUA()) 678 .header("User-Agent", Utils.getCustomUA())
679 .header("Content-Type", "application/json") 679 .header("Content-Type", "application/json")
680 .addHeader("token", APIResponse.getInstance().getToken()) 680 .addHeader("token", APIResponse.getInstance().getToken())
681 .get(); 681 .get();
682 682
683 OkHttpClient httpClient = new OkHttpClient.Builder() 683 OkHttpClient httpClient = new OkHttpClient.Builder()
684 .readTimeout(30, TimeUnit.SECONDS) 684 .readTimeout(30, TimeUnit.SECONDS)
685 .writeTimeout(30, TimeUnit.SECONDS) 685 .writeTimeout(30, TimeUnit.SECONDS)
686 .connectTimeout(30, TimeUnit.SECONDS) 686 .connectTimeout(30, TimeUnit.SECONDS)
687 .build(); 687 .build();
688 688
689 String jsonString = null; 689 String jsonString = null;
690 try { 690 try {
691 Response response = httpClient.newCall(request.build()).execute(); 691 Response response = httpClient.newCall(request.build()).execute();
692 if (response == null) { 692 if (response == null) {
693 action.onError(null); 693 action.onError(null);
694 Debug.error("Response is null"); 694 Debug.error("Response is null");
695 return null; 695 return null;
696 } 696 }
697 jsonString = getResponseData(response.body()); 697 jsonString = getResponseData(response.body());
698 698
699 } catch (IOException e) { 699 } catch (IOException e) {
700 Debug.normal("Error %s", e.getMessage()); 700 Debug.normal("Error %s", e.getMessage());
701 } 701 }
702 return jsonString; 702 return jsonString;
703 } 703 }
704 704
705 @Override 705 @Override
706 protected void onCancelled() { 706 protected void onCancelled() {
707 super.onCancelled(); 707 super.onCancelled();
708 action.onError(null); 708 action.onError(null);
709 } 709 }
710 710
711 @Override 711 @Override
712 protected void onPostExecute(String jsonString) { 712 protected void onPostExecute(String jsonString) {
713 super.onPostExecute(jsonString); 713 super.onPostExecute(jsonString);
714 if ((jsonString == null) || (jsonString.isEmpty())) { 714 if ((jsonString == null) || (jsonString.isEmpty())) {
715 action.onError(null); 715 action.onError(null);
716 return; 716 return;
717 } 717 }
718 Debug.normal("String body: "+jsonString); 718 Debug.normal("String body: "+jsonString);
719 719
720 try { 720 try {
721 JSONObject jsonObject = new JSONObject(jsonString); 721 JSONObject jsonObject = new JSONObject(jsonString);
722 int status = jsonObject.optInt("status"); 722 int status = jsonObject.optInt("status");
723 if (status == 1) { 723 if (status == 1) {
724 action.onSuccess(jsonString); 724 action.onSuccess(jsonString);
725 } else { 725 } else {
726 action.onError(new Error(jsonObject.getString("message"))); 726 action.onError(new Error(jsonObject.getString("message")));
727 } 727 }
728 } catch (JSONException e) { 728 } catch (JSONException e) {
729 action.onError(null); 729 action.onError(null);
730 } 730 }
731 } 731 }
732 } 732 }
733 733
734 public static class HistoryDetail extends AsyncTask<Void, Void, String>{ 734 public static class HistoryDetail extends AsyncTask<Void, Void, String>{
735 private Date fromDate; 735 private Date fromDate;
736 private Date toDate; 736 private Date toDate;
737 private LLAPIManagerListener action; 737 private LLAPIManagerListener action;
738 738
739 public HistoryDetail(Date fromDate, Date toDate, LLAPIManagerListener action) { 739 public HistoryDetail(Date fromDate, Date toDate, LLAPIManagerListener action) {
740 this.fromDate = fromDate; 740 this.fromDate = fromDate;
741 this.toDate = toDate; 741 this.toDate = toDate;
742 this.action = action; 742 this.action = action;
743 } 743 }
744 744
745 @Override 745 @Override
746 protected void onPreExecute() { 746 protected void onPreExecute() {
747 super.onPreExecute(); 747 super.onPreExecute();
748 } 748 }
749 749
750 @Override 750 @Override
751 protected String doInBackground(Void... voids) { 751 protected String doInBackground(Void... voids) {
752 752
753 String fromStr = Utils.dateToStringFormatDayMonthYear(fromDate); 753 String fromStr = Utils.dateToStringFormatDayMonthYear(fromDate);
754 String toStr = Utils.dateToStringFormatDayMonthYear(toDate); 754 String toStr = Utils.dateToStringFormatDayMonthYear(toDate);
755 Debug.normal("Token: "+ APIResponse.getInstance().getToken()); 755 Debug.normal("Token: "+ APIResponse.getInstance().getToken());
756 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_HISTORE_DETAIL_INFO + "/"+ fromStr +"/"+ toStr); 756 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_HISTORE_DETAIL_INFO + "/"+ fromStr +"/"+ toStr);
757 Debug.normal("URL: "+baseUrl.toString()); 757 Debug.normal("URL: "+baseUrl.toString());
758 final Request.Builder request = new Request.Builder() 758 final Request.Builder request = new Request.Builder()
759 .url(baseUrl) 759 .url(baseUrl)
760 .header("User-Agent", Utils.getCustomUA()) 760 .header("User-Agent", Utils.getCustomUA())
761 .header("Content-Type", "application/json") 761 .header("Content-Type", "application/json")
762 .addHeader("token", APIResponse.getInstance().getToken()) 762 .addHeader("token", APIResponse.getInstance().getToken())
763 .get(); 763 .get();
764 764
765 OkHttpClient httpClient = new OkHttpClient.Builder() 765 OkHttpClient httpClient = new OkHttpClient.Builder()
766 .readTimeout(30, TimeUnit.SECONDS) 766 .readTimeout(30, TimeUnit.SECONDS)
767 .writeTimeout(30, TimeUnit.SECONDS) 767 .writeTimeout(30, TimeUnit.SECONDS)
768 .connectTimeout(30, TimeUnit.SECONDS) 768 .connectTimeout(30, TimeUnit.SECONDS)
769 .build(); 769 .build();
770 770
771 String jsonString = null; 771 String jsonString = null;
772 try { 772 try {
773 Response response = httpClient.newCall(request.build()).execute(); 773 Response response = httpClient.newCall(request.build()).execute();
774 if (response == null) { 774 if (response == null) {
775 action.onError(null); 775 action.onError(null);
776 Debug.error("Response is null"); 776 Debug.error("Response is null");
777 return null; 777 return null;
778 } 778 }
779 jsonString = getResponseData(response.body()); 779 jsonString = getResponseData(response.body());
780 780
781 } catch (IOException e) { 781 } catch (IOException e) {
782 Debug.normal("Error %s", e.getMessage()); 782 Debug.normal("Error %s", e.getMessage());
783 } 783 }
784 return jsonString; 784 return jsonString;
785 } 785 }
786 786
787 @Override 787 @Override
788 protected void onCancelled() { 788 protected void onCancelled() {
789 super.onCancelled(); 789 super.onCancelled();
790 action.onError(null); 790 action.onError(null);
791 } 791 }
792 792
793 @Override 793 @Override
794 protected void onPostExecute(String jsonString) { 794 protected void onPostExecute(String jsonString) {
795 super.onPostExecute(jsonString); 795 super.onPostExecute(jsonString);
796 if ((jsonString == null) || (jsonString.isEmpty())) { 796 if ((jsonString == null) || (jsonString.isEmpty())) {
797 action.onError(null); 797 action.onError(null);
798 return; 798 return;
799 } 799 }
800 Debug.normal("String body: "+jsonString); 800 Debug.normal("String body: "+jsonString);
801 801
802 try { 802 try {
803 JSONObject jsonObject = new JSONObject(jsonString); 803 JSONObject jsonObject = new JSONObject(jsonString);
804 int status = jsonObject.optInt("status"); 804 int status = jsonObject.optInt("status");
805 if (status == 1) { 805 if (status == 1) {
806 action.onSuccess(jsonString); 806 action.onSuccess(jsonString);
807 } else { 807 } else {
808 action.onError(new Error(jsonObject.getString("message"))); 808 action.onError(new Error(jsonObject.getString("message")));
809 } 809 }
810 } catch (JSONException e) { 810 } catch (JSONException e) {
811 action.onError(null); 811 action.onError(null);
812 } 812 }
813 } 813 }
814 814
815 } 815 }
816 816
817 public static class HomePage extends AsyncTask<Void, Void, String>{ 817 public static class HomePage extends AsyncTask<Void, Void, String>{
818 private Date date; 818 private Date date;
819 private Const.STEP_TYPE stepType; 819 private Const.STEP_TYPE stepType;
820 private LLAPIManagerListener action; 820 private LLAPIManagerListener action;
821 821
822 public HomePage(Date date, Const.STEP_TYPE stepType, LLAPIManagerListener action) { 822 public HomePage(Date date, Const.STEP_TYPE stepType, LLAPIManagerListener action) {
823 this.date = date; 823 this.date = date;
824 this.stepType = stepType; 824 this.stepType = stepType;
825 this.action = action; 825 this.action = action;
826 } 826 }
827 827
828 @Override 828 @Override
829 protected void onPreExecute() { 829 protected void onPreExecute() {
830 super.onPreExecute(); 830 super.onPreExecute();
831 } 831 }
832 832
833 @Override 833 @Override
834 protected String doInBackground(Void... voids) { 834 protected String doInBackground(Void... voids) {
835 835
836 String dateStr = Utils.dateToStringFormatDayMonthYear(date); 836 String dateStr = Utils.dateToStringFormatDayMonthYear(date);
837 Debug.normal("Token: "+ APIResponse.getInstance().getToken()); 837 Debug.normal("Token: "+ APIResponse.getInstance().getToken());
838 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_HOME_INFO + "/"+ stepType.value +"/"+ dateStr); 838 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_HOME_INFO + "/"+ stepType.value +"/"+ dateStr);
839 Debug.normal("URL: "+baseUrl.toString()); 839 Debug.normal("URL: "+baseUrl.toString());
840 final Request.Builder request = new Request.Builder() 840 final Request.Builder request = new Request.Builder()
841 .url(baseUrl) 841 .url(baseUrl)
842 .header("User-Agent", Utils.getCustomUA()) 842 .header("User-Agent", Utils.getCustomUA())
843 .header("Content-Type", "application/json") 843 .header("Content-Type", "application/json")
844 .addHeader("token", APIResponse.getInstance().getToken()) 844 .addHeader("token", APIResponse.getInstance().getToken())
845 .get(); 845 .get();
846 846
847 OkHttpClient httpClient = new OkHttpClient.Builder() 847 OkHttpClient httpClient = new OkHttpClient.Builder()
848 .readTimeout(30, TimeUnit.SECONDS) 848 .readTimeout(30, TimeUnit.SECONDS)
849 .writeTimeout(30, TimeUnit.SECONDS) 849 .writeTimeout(30, TimeUnit.SECONDS)
850 .connectTimeout(30, TimeUnit.SECONDS) 850 .connectTimeout(30, TimeUnit.SECONDS)
851 .build(); 851 .build();
852 852
853 String jsonString = null; 853 String jsonString = null;
854 try { 854 try {
855 Response response = httpClient.newCall(request.build()).execute(); 855 Response response = httpClient.newCall(request.build()).execute();
856 if (response == null) { 856 if (response == null) {
857 action.onError(null); 857 action.onError(null);
858 Debug.error("Response is null"); 858 Debug.error("Response is null");
859 return null; 859 return null;
860 } 860 }
861 jsonString = getResponseData(response.body()); 861 jsonString = getResponseData(response.body());
862 862
863 } catch (IOException e) { 863 } catch (IOException e) {
864 Debug.normal("Error %s", e.getMessage()); 864 Debug.normal("Error %s", e.getMessage());
865 } 865 }
866 return jsonString; 866 return jsonString;
867 } 867 }
868 868
869 @Override 869 @Override
870 protected void onCancelled() { 870 protected void onCancelled() {
871 super.onCancelled(); 871 super.onCancelled();
872 action.onError(null); 872 action.onError(null);
873 } 873 }
874 874
875 @Override 875 @Override
876 protected void onPostExecute(String jsonString) { 876 protected void onPostExecute(String jsonString) {
877 super.onPostExecute(jsonString); 877 super.onPostExecute(jsonString);
878 if ((jsonString == null) || (jsonString.isEmpty())) { 878 if ((jsonString == null) || (jsonString.isEmpty())) {
879 action.onError(null); 879 action.onError(null);
880 return; 880 return;
881 } 881 }
882 Debug.normal("String body: "+jsonString); 882 Debug.normal("String body: "+jsonString);
883 883
884 try { 884 try {
885 JSONObject jsonObject = new JSONObject(jsonString); 885 JSONObject jsonObject = new JSONObject(jsonString);
886 int status = jsonObject.optInt("status"); 886 int status = jsonObject.optInt("status");
887 if (status == 1) { 887 if (status == 1) {
888 action.onSuccess(jsonString); 888 action.onSuccess(jsonString);
889 } else { 889 } else {
890 action.onError(new Error(jsonObject.getString("message"))); 890 action.onError(new Error(jsonObject.getString("message")));
891 } 891 }
892 } catch (JSONException e) { 892 } catch (JSONException e) {
893 action.onError(null); 893 action.onError(null);
894 } 894 }
895 } 895 }
896 896
897 } 897 }
898 898
899 public static class TopInfo extends AsyncTask<Void, Void, String>{ 899 public static class TopInfo extends AsyncTask<Void, Void, String>{
900 private Date date; 900 private Date date;
901 private Const.STEP_TYPE stepType; 901 private Const.STEP_TYPE stepType;
902 private LLAPIManagerListener action; 902 private LLAPIManagerListener action;
903 903
904 public TopInfo(Date date, Const.STEP_TYPE stepType, LLAPIManagerListener action) { 904 public TopInfo(Date date, Const.STEP_TYPE stepType, LLAPIManagerListener action) {
905 this.date = date; 905 this.date = date;
906 this.stepType = stepType; 906 this.stepType = stepType;
907 this.action = action; 907 this.action = action;
908 } 908 }
909 909
910 @Override 910 @Override
911 protected void onPreExecute() { 911 protected void onPreExecute() {
912 super.onPreExecute(); 912 super.onPreExecute();
913 } 913 }
914 914
915 @Override 915 @Override
916 protected String doInBackground(Void... voids) { 916 protected String doInBackground(Void... voids) {
917 917
918 String dateStr = Utils.dateToStringFormatDayMonthYear(date); 918 String dateStr = Utils.dateToStringFormatDayMonthYear(date);
919 Debug.normal("Token: "+ APIResponse.getInstance().getToken()); 919 Debug.normal("Token: "+ APIResponse.getInstance().getToken());
920 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_TOP_INFO + "/"+ stepType.value +"/"+ dateStr); 920 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_TOP_INFO + "/"+ stepType.value +"/"+ dateStr);
921 Debug.normal("URL: "+baseUrl.toString()); 921 Debug.normal("URL: "+baseUrl.toString());
922 final Request.Builder request = new Request.Builder() 922 final Request.Builder request = new Request.Builder()
923 .url(baseUrl) 923 .url(baseUrl)
924 .header("User-Agent", Utils.getCustomUA()) 924 .header("User-Agent", Utils.getCustomUA())
925 .header("Content-Type", "application/json") 925 .header("Content-Type", "application/json")
926 .addHeader("token", APIResponse.getInstance().getToken()) 926 .addHeader("token", APIResponse.getInstance().getToken())
927 .get(); 927 .get();
928 928
929 OkHttpClient httpClient = new OkHttpClient.Builder() 929 OkHttpClient httpClient = new OkHttpClient.Builder()
930 .readTimeout(30, TimeUnit.SECONDS) 930 .readTimeout(30, TimeUnit.SECONDS)
931 .writeTimeout(30, TimeUnit.SECONDS) 931 .writeTimeout(30, TimeUnit.SECONDS)
932 .connectTimeout(30, TimeUnit.SECONDS) 932 .connectTimeout(30, TimeUnit.SECONDS)
933 .build(); 933 .build();
934 934
935 String jsonString = null; 935 String jsonString = null;
936 try { 936 try {
937 Response response = httpClient.newCall(request.build()).execute(); 937 Response response = httpClient.newCall(request.build()).execute();
938 if (response == null) { 938 if (response == null) {
939 action.onError(null); 939 action.onError(null);
940 Debug.error("Response is null"); 940 Debug.error("Response is null");
941 return null; 941 return null;
942 } 942 }
943 jsonString = getResponseData(response.body()); 943 jsonString = getResponseData(response.body());
944 944
945 } catch (IOException e) { 945 } catch (IOException e) {
946 Debug.normal("Error %s", e.getMessage()); 946 Debug.normal("Error %s", e.getMessage());
947 } 947 }
948 return jsonString; 948 return jsonString;
949 } 949 }
950 950
951 @Override 951 @Override
952 protected void onCancelled() { 952 protected void onCancelled() {
953 super.onCancelled(); 953 super.onCancelled();
954 action.onError(null); 954 action.onError(null);
955 } 955 }
956 956
957 @Override 957 @Override
958 protected void onPostExecute(String jsonString) { 958 protected void onPostExecute(String jsonString) {
959 super.onPostExecute(jsonString); 959 super.onPostExecute(jsonString);
960 if ((jsonString == null) || (jsonString.isEmpty())) { 960 if ((jsonString == null) || (jsonString.isEmpty())) {
961 action.onError(null); 961 action.onError(null);
962 return; 962 return;
963 } 963 }
964 Debug.normal("String body: "+jsonString); 964 Debug.normal("String body: "+jsonString);
965 965
966 try { 966 try {
967 JSONObject jsonObject = new JSONObject(jsonString); 967 JSONObject jsonObject = new JSONObject(jsonString);
968 int status = jsonObject.optInt("status"); 968 int status = jsonObject.optInt("status");
969 if (status == 1) { 969 if (status == 1) {
970 action.onSuccess(jsonString); 970 action.onSuccess(jsonString);
971 } else { 971 } else {
972 action.onError(new Error(jsonObject.getString("message"))); 972 action.onError(new Error(jsonObject.getString("message")));
973 } 973 }
974 } catch (JSONException e) { 974 } catch (JSONException e) {
975 action.onError(null); 975 action.onError(null);
976 } 976 }
977 } 977 }
978 978
979 } 979 }
980 980
981 public static class CreateLog extends AsyncTask<Void, Void, String>{ 981 public static class CreateLog extends AsyncTask<Void, Void, String>{
982 private int stepCount; 982 private int stepCount;
983 private Const.STEP_TYPE stepType; 983 private Const.STEP_TYPE stepType;
984 private Date startTime; 984 private Date startTime;
985 private Date endTime; 985 private Date endTime;
986 private LLAPIManagerListener action; 986 private LLAPIManagerListener action;
987 987
988 public CreateLog(Const.STEP_TYPE stepType, int stepCount, Date startTime, Date endTime, LLAPIManagerListener action) { 988 public CreateLog(Const.STEP_TYPE stepType, int stepCount, Date startTime, Date endTime, LLAPIManagerListener action) {
989 this.stepCount = stepCount; 989 this.stepCount = stepCount;
990 this.stepType = stepType; 990 this.stepType = stepType;
991 this.startTime = startTime; 991 this.startTime = startTime;
992 this.endTime = endTime; 992 this.endTime = endTime;
993 this.action = action; 993 this.action = action;
994 } 994 }
995 995
996 996
997 @Override 997 @Override
998 protected void onPreExecute() { 998 protected void onPreExecute() {
999 super.onPreExecute(); 999 super.onPreExecute();
1000
1000 } 1001 }
1001 1002
1002 @Override 1003 @Override
1003 protected String doInBackground(Void... voids) { 1004 protected String doInBackground(Void... voids) {
1004 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_CREATE_LOG_INFO); 1005 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_CREATE_LOG_INFO);
1005 JSONObject jsonObject = new JSONObject(); 1006 JSONObject jsonObject = new JSONObject();
1006 String startT = Utils.convertDate2DateTimeString(startTime); 1007 String startT = Utils.convertDate2DateTimeString(startTime);
1007 String endT = Utils.convertDate2DateTimeString(endTime); 1008 String endT = Utils.convertDate2DateTimeString(endTime);
1008 try { 1009 try {
1009 jsonObject.put("mode", stepType.value); 1010 jsonObject.put("mode", stepType.value);
1010 jsonObject.put("numStep", stepCount); 1011 jsonObject.put("numStep", stepCount);
1011 jsonObject.put("startTime", startT); 1012 jsonObject.put("startTime", startT);
1012 jsonObject.put("endTime", endT); 1013 jsonObject.put("endTime", endT);
1013 1014
1014 Debug.warn("Json data: " + jsonObject.toString()); 1015 Debug.warn("Json data: " + jsonObject.toString());
1015 } catch (JSONException e) { 1016 } catch (JSONException e) {
1016 Debug.normal("Error ", e.getMessage()); 1017 Debug.normal("Error ", e.getMessage());
1017 } 1018 }
1018 1019
1019 MediaType JSON 1020 MediaType JSON
1020 = MediaType.parse("application/json"); 1021 = MediaType.parse("application/json");
1021 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 1022 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
1022 1023
1024 Debug.warn("token data: " + APIResponse.getInstance().getToken());
1023 final Request.Builder request = new Request.Builder() 1025 final Request.Builder request = new Request.Builder()
1024 .url(baseUrl) 1026 .url(baseUrl)
1025 .header("User-Agent", Utils.getCustomUA()) 1027 .header("User-Agent", Utils.getCustomUA())
1026 .header("Content-Type", "application/json") 1028 .header("Content-Type", "application/json")
1027 .addHeader("token", APIResponse.getInstance().getToken()) 1029 .addHeader("token", APIResponse.getInstance().getToken())
1028 .post(requestBody); 1030 .post(requestBody);
1029 1031
1030 OkHttpClient httpClient = new OkHttpClient.Builder() 1032 OkHttpClient httpClient = new OkHttpClient.Builder()
1031 .readTimeout(30, TimeUnit.SECONDS) 1033 .readTimeout(30, TimeUnit.SECONDS)
1032 .writeTimeout(30, TimeUnit.SECONDS) 1034 .writeTimeout(30, TimeUnit.SECONDS)
1033 .connectTimeout(30, TimeUnit.SECONDS) 1035 .connectTimeout(30, TimeUnit.SECONDS)
1034 .build(); 1036 .build();
1035 1037
1036 String jsonString = null; 1038 String jsonString = null;
1037 try { 1039 try {
1038 Response response = httpClient.newCall(request.build()).execute(); 1040 Response response = httpClient.newCall(request.build()).execute();
1039 if (response == null) { 1041 if (response == null) {
1040 action.onError(null); 1042 action.onError(null);
1041 Debug.error("Response is null"); 1043 Debug.error("Response is null");
1042 return null; 1044 return null;
1043 } 1045 }
1044 jsonString = getResponseData(response.body()); 1046 jsonString = getResponseData(response.body());
1045 1047
1046 } catch (IOException e) { 1048 } catch (IOException e) {
1047 Debug.normal("Error %s", e.getMessage()); 1049 Debug.normal("Error %s", e.getMessage());
1048 } 1050 }
1049 return jsonString; 1051 return jsonString;
1050 } 1052 }
1051 1053
1052 @Override 1054 @Override
1053 protected void onCancelled() { 1055 protected void onCancelled() {
1054 super.onCancelled(); 1056 super.onCancelled();
1055 action.onError(null); 1057 action.onError(null);
1056 } 1058 }
1057 1059
1058 @Override 1060 @Override
1059 protected void onPostExecute(String jsonString) { 1061 protected void onPostExecute(String jsonString) {
1060 super.onPostExecute(jsonString); 1062 super.onPostExecute(jsonString);
1061 if ((jsonString == null) || (jsonString.isEmpty())) { 1063 if ((jsonString == null) || (jsonString.isEmpty())) {
1062 action.onError(null); 1064 action.onError(null);
1063 return; 1065 return;
1064 } 1066 }
1065 Debug.normal("String body: "+jsonString); 1067 Debug.normal("String body: "+jsonString);
1066 1068
1067 try { 1069 try {
1068 JSONObject jsonObject = new JSONObject(jsonString); 1070 JSONObject jsonObject = new JSONObject(jsonString);
1069 int status = jsonObject.optInt("status"); 1071 int status = jsonObject.optInt("status");
1070 if (status == 1) { 1072 if (status == 1) {
1071 action.onSuccess(jsonString); 1073 action.onSuccess(jsonString);
1072 } else { 1074 } else {
1073 action.onError(new Error(jsonObject.getString("message"))); 1075 action.onError(new Error(jsonObject.getString("message")));
1074 } 1076 }
1075 } catch (JSONException e) { 1077 } catch (JSONException e) {
1076 action.onError(null); 1078 action.onError(null);
1077 } 1079 }
1078 } 1080 }
1079 } 1081 }
1080 1082
1081 public static class RefreshToken extends AsyncTask<Void, Void, String>{ 1083 public static class RefreshToken extends AsyncTask<Void, Void, String>{
1082 private Context context; 1084 private Context context;
1083 private int userId; 1085 private int userId;
1084 private LLAPIManagerListener action; 1086 private LLAPIManagerListener action;
1085 1087
1086 public RefreshToken(Context context, int userId, LLAPIManagerListener action) { 1088 public RefreshToken(Context context, int userId, LLAPIManagerListener action) {
1087 this.context = context; 1089 this.context = context;
1088 this.userId = userId; 1090 this.userId = userId;
1089 this.action = action; 1091 this.action = action;
1090 } 1092 }
1091 1093
1092 @Override 1094 @Override
1093 protected void onPreExecute() { 1095 protected void onPreExecute() {
1094 super.onPreExecute(); 1096 super.onPreExecute();
1095 } 1097 }
1096 1098
1097 @Override 1099 @Override
1098 protected String doInBackground(Void... voids) { 1100 protected String doInBackground(Void... voids) {
1099 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_REFESH_TOKEN_INFO); 1101 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_REFESH_TOKEN_INFO);
1100 JSONObject jsonObject = new JSONObject(); 1102 JSONObject jsonObject = new JSONObject();
1101 try { 1103 try {
1102 //Personal info 1104 //Personal info
1103 jsonObject.put("userId", userId); 1105 jsonObject.put("userId", userId);
1104 1106
1105 Debug.warn("Json data: " + jsonObject.toString()); 1107 Debug.warn("Json data: " + jsonObject.toString());
1106 } catch (JSONException e) { 1108 } catch (JSONException e) {
1107 Debug.normal("Error ", e.getMessage()); 1109 Debug.normal("Error ", e.getMessage());
1108 } 1110 }
1109 1111
1110 MediaType JSON 1112 MediaType JSON
1111 = MediaType.parse("application/json"); 1113 = MediaType.parse("application/json");
1112 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); 1114 RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
1113 1115
1114 final Request.Builder request = new Request.Builder() 1116 final Request.Builder request = new Request.Builder()
1115 .url(baseUrl) 1117 .url(baseUrl)
1116 .header("User-Agent", Utils.getCustomUA()) 1118 .header("User-Agent", Utils.getCustomUA())
1117 .header("Content-Type", "application/json") 1119 .header("Content-Type", "application/json")
1118 .post(requestBody); 1120 .post(requestBody);
1119 1121
1120 OkHttpClient httpClient = new OkHttpClient.Builder() 1122 OkHttpClient httpClient = new OkHttpClient.Builder()
1121 .readTimeout(30, TimeUnit.SECONDS) 1123 .readTimeout(30, TimeUnit.SECONDS)
1122 .writeTimeout(30, TimeUnit.SECONDS) 1124 .writeTimeout(30, TimeUnit.SECONDS)
1123 .connectTimeout(30, TimeUnit.SECONDS) 1125 .connectTimeout(30, TimeUnit.SECONDS)
1124 .build(); 1126 .build();
1125 1127
1126 String jsonString = null; 1128 String jsonString = null;
1127 try { 1129 try {
1128 Response response = httpClient.newCall(request.build()).execute(); 1130 Response response = httpClient.newCall(request.build()).execute();
1129 if (response == null) { 1131 if (response == null) {
1130 action.onError(null); 1132 action.onError(null);
1131 Debug.error("Response is null"); 1133 Debug.error("Response is null");
1132 return null; 1134 return null;
1133 } 1135 }
1134 jsonString = getResponseData(response.body()); 1136 jsonString = getResponseData(response.body());
1135 1137
1136 } catch (IOException e) { 1138 } catch (IOException e) {
1137 Debug.normal("Error %s", e.getMessage()); 1139 Debug.normal("Error %s", e.getMessage());
1138 } 1140 }
1139 return jsonString; 1141 return jsonString;
1140 } 1142 }
1141 1143
1142 @Override 1144 @Override
1143 protected void onCancelled() { 1145 protected void onCancelled() {
1144 super.onCancelled(); 1146 super.onCancelled();
1145 action.onError(null); 1147 action.onError(null);
1146 } 1148 }
1147 1149
1148 @Override 1150 @Override
1149 protected void onPostExecute(String jsonString) { 1151 protected void onPostExecute(String jsonString) {
1150 super.onPostExecute(jsonString); 1152 super.onPostExecute(jsonString);
1151 if ((jsonString == null) || (jsonString.isEmpty())) { 1153 if ((jsonString == null) || (jsonString.isEmpty())) {
1152 action.onError(null); 1154 action.onError(null);
1153 return; 1155 return;
1154 } 1156 }
1155 Debug.normal("String body: "+jsonString); 1157 Debug.normal("String body: "+jsonString);
1156 1158
1157 try { 1159 try {
1158 JSONObject jsonObject = new JSONObject(jsonString); 1160 JSONObject jsonObject = new JSONObject(jsonString);
1159 int status = jsonObject.optInt("status"); 1161 int status = jsonObject.optInt("status");
1160 if (status == 1) { 1162 if (status == 1) {
1161 JSONArray tokenArr = jsonObject.optJSONArray("result"); 1163 JSONArray tokenArr = jsonObject.optJSONArray("result");
1162 String token = tokenArr.get(0).toString(); 1164 String token = tokenArr.get(0).toString();
1163 Debug.normal("Refresh Token: "+ token); 1165 Debug.normal("Refresh Token: "+ token);
1164 // save data 1166 // save data
1165 Setting.setUserDataSharepre(context, Setting.TOKEN_SHAREPRE, token); 1167 Setting.setUserDataSharepre(context, Setting.TOKEN_SHAREPRE, token);
1166 APIResponse.getInstance().setToken(token); 1168 APIResponse.getInstance().setToken(token);
1167 action.onSuccess(jsonString); 1169 action.onSuccess(jsonString);
1168 } else { 1170 } else {
1169 action.onError(new Error(jsonObject.getString("message"))); 1171 action.onError(new Error(jsonObject.getString("message")));
1170 } 1172 }
1171 } catch (JSONException e) { 1173 } catch (JSONException e) {
1172 action.onError(null); 1174 action.onError(null);
1173 } 1175 }
1174 } 1176 }
1175 } 1177 }
1176 1178
1177 public static class GetNews extends AsyncTask<Void, Void, String>{ 1179 public static class GetNews extends AsyncTask<Void, Void, String>{
1178 private Date date; 1180 private Date date;
1179 private LLAPIManagerListener action; 1181 private LLAPIManagerListener action;
1180 1182
1181 public GetNews(Date date, LLAPIManagerListener action) { 1183 public GetNews(Date date, LLAPIManagerListener action) {
1182 this.date = date; 1184 this.date = date;
1183 this.action = action; 1185 this.action = action;
1184 } 1186 }
1185 1187
1186 @Override 1188 @Override
1187 protected void onPreExecute() { 1189 protected void onPreExecute() {
1188 super.onPreExecute(); 1190 super.onPreExecute();
1189 } 1191 }
1190 1192
1191 @Override 1193 @Override
1192 protected String doInBackground(Void... voids) { 1194 protected String doInBackground(Void... voids) {
1193 String fromStr = Utils.dateToStringFormatDayMonthYear(date); 1195 String fromStr = Utils.dateToStringFormatDayMonthYear(date);
1194 Debug.normal("Token: "+ APIResponse.getInstance().getToken()); 1196 Debug.normal("Token: "+ APIResponse.getInstance().getToken());
1195 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_GET_NEWS_INFO + "/"+ fromStr); 1197 HttpUrl baseUrl = HttpUrl.parse(URL_ROOT + URL_GET_NEWS_INFO + "/"+ fromStr);
1196 Debug.normal("URL: "+baseUrl.toString()); 1198 Debug.normal("URL: "+baseUrl.toString());
1197 final Request.Builder request = new Request.Builder() 1199 final Request.Builder request = new Request.Builder()
1198 .url(baseUrl) 1200 .url(baseUrl)
1199 .header("User-Agent", Utils.getCustomUA()) 1201 .header("User-Agent", Utils.getCustomUA())
1200 .header("Content-Type", "application/json") 1202 .header("Content-Type", "application/json")
1201 .addHeader("token", APIResponse.getInstance().getToken()) 1203 .addHeader("token", APIResponse.getInstance().getToken())
1202 .get(); 1204 .get();
1203 1205
1204 OkHttpClient httpClient = new OkHttpClient.Builder() 1206 OkHttpClient httpClient = new OkHttpClient.Builder()
1205 .readTimeout(30, TimeUnit.SECONDS) 1207 .readTimeout(30, TimeUnit.SECONDS)
1206 .writeTimeout(30, TimeUnit.SECONDS) 1208 .writeTimeout(30, TimeUnit.SECONDS)
1207 .connectTimeout(30, TimeUnit.SECONDS) 1209 .connectTimeout(30, TimeUnit.SECONDS)
1208 .build(); 1210 .build();
1209 1211
1210 String jsonString = null; 1212 String jsonString = null;
1211 try { 1213 try {
1212 Response response = httpClient.newCall(request.build()).execute(); 1214 Response response = httpClient.newCall(request.build()).execute();
1213 if (response == null) { 1215 if (response == null) {
1214 action.onError(null); 1216 action.onError(null);
1215 Debug.error("Response is null"); 1217 Debug.error("Response is null");
1216 return null; 1218 return null;
1217 } 1219 }
1218 jsonString = getResponseData(response.body()); 1220 jsonString = getResponseData(response.body());
1219 1221
1220 } catch (IOException e) { 1222 } catch (IOException e) {
1221 Debug.normal("Error %s", e.getMessage()); 1223 Debug.normal("Error %s", e.getMessage());
1222 } 1224 }
1223 return jsonString; 1225 return jsonString;
1224 } 1226 }
1225 1227
1226 @Override 1228 @Override
1227 protected void onCancelled() { 1229 protected void onCancelled() {
1228 super.onCancelled(); 1230 super.onCancelled();
1229 action.onError(null); 1231 action.onError(null);
1230 } 1232 }
1231 1233
1232 @Override 1234 @Override
1233 protected void onPostExecute(String jsonString) { 1235 protected void onPostExecute(String jsonString) {
1234 super.onPostExecute(jsonString); 1236 super.onPostExecute(jsonString);
1235 if ((jsonString == null) || (jsonString.isEmpty())) { 1237 if ((jsonString == null) || (jsonString.isEmpty())) {
1236 action.onError(null); 1238 action.onError(null);
1237 return; 1239 return;
1238 } 1240 }
1239 Debug.normal("String body: "+jsonString); 1241 Debug.normal("String body: "+jsonString);
1240 1242
1241 try { 1243 try {
1242 JSONObject jsonObject = new JSONObject(jsonString); 1244 JSONObject jsonObject = new JSONObject(jsonString);
1243 int status = jsonObject.optInt("status"); 1245 int status = jsonObject.optInt("status");
1244 if (status == 1) { 1246 if (status == 1) {
1245 // save data 1247 // save data
1246 action.onSuccess(jsonString); 1248 action.onSuccess(jsonString);
1247 } else { 1249 } else {
1248 action.onError(new Error(jsonObject.getString("message"))); 1250 action.onError(new Error(jsonObject.getString("message")));
1249 } 1251 }
1250 } catch (JSONException e) { 1252 } catch (JSONException e) {
1251 action.onError(null); 1253 action.onError(null);
1252 } 1254 }
1253 } 1255 }
1254 } 1256 }
1255 1257
1256 public static Bitmap getBitmapFromAsset(Context context, String filePath) { 1258 public static Bitmap getBitmapFromAsset(Context context, String filePath) {
1257 AssetManager assetManager = context.getAssets(); 1259 AssetManager assetManager = context.getAssets();
1258 InputStream istr; 1260 InputStream istr;
1259 Bitmap bitmap = null; 1261 Bitmap bitmap = null;
1260 try { 1262 try {
1261 istr = assetManager.open(filePath); 1263 istr = assetManager.open(filePath);
1262 bitmap = BitmapFactory.decodeStream(istr); 1264 bitmap = BitmapFactory.decodeStream(istr);
1263 } catch (IOException e) { 1265 } catch (IOException e) {
1264 Debug.normal("error: %s", e.getMessage()); 1266 Debug.normal("error: %s", e.getMessage());
1265 } 1267 }
1266 return bitmap; 1268 return bitmap;
1267 } 1269 }
1268 1270
1269 public static String getResponseData(ResponseBody response) { 1271 public static String getResponseData(ResponseBody response) {
1270 1272
1271 String unzipString = ""; 1273 String unzipString = "";
1272 try { 1274 try {
1273 unzipString = response.string(); 1275 unzipString = response.string();
1274 Debug.normal("RESPONSE: "+unzipString); 1276 Debug.normal("RESPONSE: "+unzipString);
1275 } catch (IOException e) { 1277 } catch (IOException e) {
1276 e.printStackTrace(); 1278 e.printStackTrace();
1277 } 1279 }
1278 return unzipString; 1280 return unzipString;
1279 } 1281 }
1280 1282
1281 1283
1282 public static void writeToFile(String data) 1284 public static void writeToFile(String data)
1283 { 1285 {
1284 String path = 1286 String path =
1285 Environment.getExternalStorageDirectory() + File.separator + "yourFolder"; 1287 Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
1286 // Create the folder. 1288 // Create the folder.
1287 File folder = new File(path); 1289 File folder = new File(path);
1288 folder.mkdirs(); 1290 folder.mkdirs();
1289 1291
1290 // Create the file. 1292 // Create the file.
1291 File file = new File(folder, "config.txt"); 1293 File file = new File(folder, "config.txt");
1292 // Save your stream, don't forget to flush() it before closing it. 1294 // Save your stream, don't forget to flush() it before closing it.
1293 1295
1294 try 1296 try
1295 { 1297 {
1296 file.createNewFile(); 1298 file.createNewFile();
1297 FileOutputStream fOut = new FileOutputStream(file); 1299 FileOutputStream fOut = new FileOutputStream(file);
1298 OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 1300 OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
1299 myOutWriter.append(data); 1301 myOutWriter.append(data);
1300 1302
1301 myOutWriter.close(); 1303 myOutWriter.close();
1302 1304
1303 fOut.flush(); 1305 fOut.flush();
1304 fOut.close(); 1306 fOut.close();
1305 } 1307 }
1306 catch (IOException e) 1308 catch (IOException e)
1307 { 1309 {
1308 Log.e("Exception", "File write failed: " + e.toString()); 1310 Log.e("Exception", "File write failed: " + e.toString());
1309 } 1311 }
1310 } 1312 }
1311 1313
1312 private static String hashMapToUrl(HashMap<String, String> params) throws UnsupportedEncodingException { 1314 private static String hashMapToUrl(HashMap<String, String> params) throws UnsupportedEncodingException {
1313 StringBuilder result = new StringBuilder(); 1315 StringBuilder result = new StringBuilder();
1314 boolean first = true; 1316 boolean first = true;
1315 for(Map.Entry<String, String> entry : params.entrySet()){ 1317 for(Map.Entry<String, String> entry : params.entrySet()){
1316 if (first) 1318 if (first)
1317 first = false; 1319 first = false;
1318 else 1320 else
1319 result.append("&"); 1321 result.append("&");
1320 1322
1321 result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 1323 result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
1322 result.append("="); 1324 result.append("=");
1323 result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 1325 result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
1324 } 1326 }
1325 1327
1326 return result.toString(); 1328 return result.toString();
1327 } 1329 }
1328 } 1330 }
1329 1331
app/src/main/java/com/dinhcv/lifelogpedometer/utils/SensorFusionMath.java
File was created 1 package com.dinhcv.lifelogpedometer.utils;
2
3 /**
4 * Created by Administrator on 08/01/2018.
5 */
6
7 public class SensorFusionMath {
8
9 private SensorFusionMath() {
10 }
11
12 public static float sum(float[] array) {
13 float retval = 0;
14 for (int i = 0; i < array.length; i++) {
15 retval += array[i];
16 }
17 return retval;
18 }
19
20 public static float[] cross(float[] arrayA, float[] arrayB) {
21 float[] retArray = new float[3];
22 retArray[0] = arrayA[1] * arrayB[2] - arrayA[2] * arrayB[1];
23 retArray[1] = arrayA[2] * arrayB[0] - arrayA[0] * arrayB[2];
24 retArray[2] = arrayA[0] * arrayB[1] - arrayA[1] * arrayB[0];
25 return retArray;
26 }
27
28 public static float norm(float[] array) {
29 float retval = 0;
30 for (int i = 0; i < array.length; i++) {
31 retval += array[i] * array[i];
32 }
33 return (float) Math.sqrt(retval);
34 }
35
36 // Note: only works with 3D vectors.
37 public static float dot(float[] a, float[] b) {
38 float retval = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
39 return retval;
40 }
41
42 public static float[] normalize(float[] a) {
43 float[] retval = new float[a.length];
44 float norm = norm(a);
45 for (int i = 0; i < a.length; i++) {
46 retval[i] = a[i] / norm;
47 }
48 return retval;
49 }
50
51 }
app/src/main/java/com/dinhcv/lifelogpedometer/utils/SimpleStepDetector.java
File was created 1 package com.dinhcv.lifelogpedometer.utils;
2
3 import com.dinhcv.lifelogpedometer.interfaces.StepListener;
4
5 /**
6 * Created by Administrator on 08/01/2018.
7 */
8
9 public class SimpleStepDetector {
10 private static final int ACCEL_RING_SIZE = 50;
11 private static final int VEL_RING_SIZE = 10;
12 private static final float STEP_THRESHOLD = 4f;
13 private static final int STEP_DELAY_NS = 250000000;
14
15 private int accelRingCounter = 0;
16 private float[] accelRingX = new float[ACCEL_RING_SIZE];
17 private float[] accelRingY = new float[ACCEL_RING_SIZE];
18 private float[] accelRingZ = new float[ACCEL_RING_SIZE];
19 private int velRingCounter = 0;
20 private float[] velRing = new float[VEL_RING_SIZE];
21 private long lastStepTimeNs = 0;
22 private float oldVelocityEstimate = 0;
23
24 private StepListener listener;
25
26 public void registerListener(StepListener listener) {
27 this.listener = listener;
28 }
29
30 /**
31 * Accepts updates from the accelerometer.
32 */
33 public void updateAccel(long timeNs, float x, float y, float z) {
34 float[] currentAccel = new float[3];
35 currentAccel[0] = x;
36 currentAccel[1] = y;
37 currentAccel[2] = z;
38
39 // First step is to update our guess of where the global z vector is.
40 accelRingCounter++;
41 accelRingX[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[0];
42 accelRingY[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[1];
43 accelRingZ[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[2];
44
45 float[] worldZ = new float[3];
46 worldZ[0] = SensorFusionMath.sum(accelRingX) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
47 worldZ[1] = SensorFusionMath.sum(accelRingY) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
48 worldZ[2] = SensorFusionMath.sum(accelRingZ) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
49
50 float normalization_factor = SensorFusionMath.norm(worldZ);
51
52 worldZ[0] = worldZ[0] / normalization_factor;
53 worldZ[1] = worldZ[1] / normalization_factor;
54 worldZ[2] = worldZ[2] / normalization_factor;
55
56 // Next step is to figure out the component of the current acceleration
57 // in the direction of world_z and subtract gravity's contribution
58 float currentZ = SensorFusionMath.dot(worldZ, currentAccel) - normalization_factor;
59 velRingCounter++;
60 velRing[velRingCounter % VEL_RING_SIZE] = currentZ;
61
62 float velocityEstimate = SensorFusionMath.sum(velRing);
63
64 if (velocityEstimate > STEP_THRESHOLD && oldVelocityEstimate <= STEP_THRESHOLD
65 && (timeNs - lastStepTimeNs > STEP_DELAY_NS)) {
66 listener.step(timeNs);
67 lastStepTimeNs = timeNs;
68 }
69 oldVelocityEstimate = velocityEstimate;
70 }
71 }
72
73