add project adins

This commit is contained in:
Alfrid Sanjaya Leo Putra 2024-07-25 14:44:22 +07:00
commit f8f85d679d
5299 changed files with 625430 additions and 0 deletions

View file

@ -0,0 +1,401 @@
package com.adins.mss.coll.fragments.view;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TextView;
import com.adins.mss.base.crashlytics.FireCrash;
import com.adins.mss.coll.R;
import com.adins.mss.coll.api.InstallmentScheduleApi;
import com.adins.mss.coll.commons.Toaster;
import com.adins.mss.coll.commons.ViewManager;
import com.adins.mss.coll.fragments.InstallmentScheduleDetailFragment;
import com.adins.mss.coll.fragments.InstallmentScheduleFragment;
import com.adins.mss.coll.models.InstallmentScheduleResponse;
import com.adins.mss.constant.Global;
import com.adins.mss.dao.InstallmentSchedule;
import com.adins.mss.dao.TaskH;
import com.adins.mss.foundation.db.dataaccess.InstallmentScheduleDataAccess;
import com.adins.mss.foundation.db.dataaccess.TaskHDataAccess;
import com.adins.mss.foundation.dialog.NiftyDialogBuilder;
import com.adins.mss.foundation.formatter.Formatter;
import com.adins.mss.foundation.formatter.Tool;
import org.acra.ACRA;
import java.io.IOException;
import java.util.List;
/**
* Created by kusnendi.muhamad on 31/07/2017.
*/
public class InstallmentScheduleView extends ViewManager {
private Activity activity;
private Context context;
private String taskId;
private InstallmentScheduleResponse scheduleResponse;
private List<InstallmentSchedule> installmentScheduleLocalList = null;
public static InstallmentSchedule detailInstallmentSchedule;
ImageButton imageButton;
public InstallmentScheduleView(Activity activity) {
super(activity);
this.activity = activity;
this.context = activity.getApplicationContext();
}
@Override
public void onCreate() {
Bundle bundle = activity.getIntent().getExtras();
taskId = bundle.getString(Global.BUND_KEY_TASK_ID);
TaskH taskH = TaskHDataAccess.getOneTaskHeader(context, taskId);
if(taskH != null){
installmentScheduleLocalList = InstallmentScheduleDataAccess.getAllByTask(context, taskH.getUuid_task_h());
// List<InstallmentSchedule> installmentScheduleLocalAll = InstallmentScheduleDataAccess.getAll(getApplicationContext());
// connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
loadData();
imageButton = (ImageButton) activity.findViewById(R.id.imageBtnDownload);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TableLayout table = (TableLayout) findViewById(R.id.tableHeaders);
// int index = 1;
// table.removeViews(index, table.getChildCount()-1);
// loadData();
imageButton.setEnabled(false);
imageButton.setClickable(false);
try {
saveData(context, scheduleResponse);
} catch (Exception e) {
FireCrash.log(e);
ACRA.getErrorReporter().handleSilentException(new Exception("Error: Insert Installment schedule Error. "+ e.getMessage()));
}
}
});
}
}
protected void saveData(Context context, InstallmentScheduleResponse installmentSchedResp) {
if(installmentSchedResp!=null && installmentSchedResp.getStatus().getCode()==0){
List<InstallmentSchedule> installmentScheduleList = installmentSchedResp.getInstallmentScheduleList();
if(installmentScheduleList!=null && installmentScheduleList.size()>0){
TaskH taskH = TaskHDataAccess.getOneTaskHeader(context, taskId);
InstallmentScheduleDataAccess.delete(context, taskH.getUuid_task_h());
//InstallmentScheduleDataAccess.add(getApplicationContext(), installmentScheduleList);
// List<InstallmentSchedule> installmentScheduleLocalAll = InstallmentScheduleDataAccess.getAll(getApplicationContext());
for(InstallmentSchedule installmentSchedule : installmentScheduleList){
if (installmentSchedule.getUuid_installment_schedule() == null){
installmentSchedule.setUuid_installment_schedule(Tool.getUUID());
}
installmentSchedule.setUuid_task_h(taskH.getUuid_task_h());
// InstallmentScheduleDataAccess.addOrReplace(context, installmentSchedule);
}
InstallmentScheduleDataAccess.addOrReplace(context, installmentScheduleList);
}
Toaster.warning(context, "Data Saved");
}else{
Toaster.warning(context, "Cannot saved data if no data or no internet connection");
}
}
public void loadData() {
new AsyncTask<Void, Void, InstallmentScheduleResponse>() {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(activity,
"", context.getString(R.string.progressWait), true);
}
@Override
protected InstallmentScheduleResponse doInBackground(Void... params) {
InstallmentScheduleApi api = new InstallmentScheduleApi(activity);
try {
//bong 21 mei 15 - check internet connection
// if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
if(isInternetConnected(context)){
return api.request(taskId);
}
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(InstallmentScheduleResponse installmentScheduleResponse) {
super.onPostExecute(installmentScheduleResponse);
if (progressDialog!=null&&progressDialog.isShowing()){
try {
progressDialog.dismiss();
} catch (Exception e) { FireCrash.log(e);
}
}
if (installmentScheduleResponse == null) {
// NiftyDialogBuilder.getInstance(InstallmentScheduleFragment.this)
// .withMessage("Unable to retrieve data from the server - offline mode")
// .withTitle("Server Error")
// .withButton1Text("Close")
// .setButton1Click(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// //finish();
// NiftyDialogBuilder.getInstance(InstallmentScheduleFragment.this).dismiss();
// }
// })
// .show();
// return;
//bong 25 mei 15 - display local data
{
TaskH taskH = TaskHDataAccess.getOneTaskHeader(context, taskId);
if(taskH!=null){
List<InstallmentSchedule> installmentScheduleList = InstallmentScheduleDataAccess.getAllByTask(context, taskH.getUuid_task_h());
if(installmentScheduleList!=null){
TextView agreementNumber = (TextView) activity.findViewById(R.id.agreementNumber);
agreementNumber.setText(installmentScheduleList.get(0).getAgreement_no());
TableLayout table = (TableLayout) activity.findViewById(R.id.tableHeaders);
int index = 1;
for (InstallmentSchedule item : installmentScheduleList) {
View row = LayoutInflater.from(activity).inflate(R.layout.view_row_installment_schedule, table, false);
TextView no = (TextView) row.findViewById(R.id.no);
TextView dueDate = (TextView) row.findViewById(R.id.dueDate);
TextView amountInstallment = (TextView) row.findViewById(R.id.amountInstallment);
TextView amountPaid = (TextView) row.findViewById(R.id.amountPaid);
// InstallmentScheduleItem installmentScheduleItem = new InstallmentScheduleItem();
// installmentScheduleItem.setAgreementNo(item.getAgreement_no());
// installmentScheduleItem.setBranchCode(item.getBranch_code());
// installmentScheduleItem.setDtmCrt(item.getDtm_crt());
// installmentScheduleItem.setDueDate(item.getDue_date());
// installmentScheduleItem.setInstallmentAmount(item.getInstallment_amount());
// installmentScheduleItem.setInstallmentNo(item.getInstallment_no());
// installmentScheduleItem.setInterestAmound(item.getInterest_amound());
// installmentScheduleItem.setLcAdminFee(item.getLc_admin_fee());
// installmentScheduleItem.setLcAdminFeePaid(item.getLc_admin_fee_paid());
// installmentScheduleItem.setLcAdminFeeWaive(item.getLc_admin_fee_waive());
// installmentScheduleItem.setLcDays(item.getLc_days());
// installmentScheduleItem.setLcInstlAmount(item.getLc_instl_amount());
// installmentScheduleItem.setLcInstlPaid(item.getLc_instl_paid());
// installmentScheduleItem.setLcInstlWaived(item.getLc_instl_waived());
// installmentScheduleItem.setOsInterestAmount(item.getOs_interest_amount());
// installmentScheduleItem.setOsPrincipalAmount(item.getOs_principal_amount());
// installmentScheduleItem.setPrincipalAmount(item.getPrincipal_amount());
// installmentScheduleItem.setUsrCrt(item.getUsr_crt());
// installmentScheduleItem.setUuidTaskId(item.getUuid_task_h());
//row.setTag(item);
row.setTag(item);
no.setText(String.valueOf(index++));
dueDate.setText(Formatter.formatDate(item.getDue_date(), Global.DATE_STR_FORMAT));
String amtIns = item.getInstallment_amount();
if(amtIns!=null && amtIns.length()>3){
String part1 = amtIns.substring(amtIns.length()-3);
if(part1.substring(0, 1).equals("."))
{
amountInstallment.setGravity(Gravity.RIGHT);
}
}
String amtPaid = item.getInstallment_paid_amount();
if(amtPaid!=null && amtPaid.length()>3){
String part2 = amtPaid.substring(amtPaid.length()-3);
if(part2.substring(0, 1).equals("."))
{
amountPaid.setGravity(Gravity.RIGHT);
}
}
amountInstallment.setText(item.getInstallment_amount());
amountPaid.setText(item.getInstallment_paid_amount());
if (index % 2 == 1) {
row.setBackgroundResource(R.color.tv_gray_light);
} else if (index % 2 == 0) {
row.setBackgroundResource(R.color.tv_gray);
}
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
detailInstallmentSchedule = (InstallmentSchedule) v.getTag();
Intent intent = new Intent(activity, InstallmentScheduleDetailFragment.class);
// intent.putExtra(InstallmentScheduleDetailFragment.INSTALLMENT_SCHEDULE_DETAIL, detail);
activity.startActivity(intent);
}
});
table.addView(row);
}
}else{
NiftyDialogBuilder.getInstance(context)
.withMessage(context.getString(R.string.no_data_found_offline))
.withTitle(context.getString(R.string.warning_capital))
.withIcon(android.R.drawable.ic_dialog_alert)
.withButton1Text(context.getString(R.string.btnClose))
.setButton1Click(new View.OnClickListener() {
@Override
public void onClick(View v) {
//finish();
NiftyDialogBuilder.getInstance(context).dismiss();
}
})
.show();
}
}
}
}
// else{
//if (installmentScheduleResponse != null) {
else if (installmentScheduleResponse.getStatus().getCode() != 0) {
NiftyDialogBuilder.getInstance(context)
.withMessage(installmentScheduleResponse.getStatus().getMessage())
.withTitle(context.getString(R.string.server_error))
.withButton1Text(context.getString(R.string.btnClose))
.setButton1Click(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
})
.show();
return;
}
// }
// //bong 21 mei 15 - if failed get data from server - use local data
// if(installmentScheduleResponse==null){
// installmentScheduleResponse = new InstallmentScheduleResponse();
// installmentScheduleResponse.setInstallmentScheduleList(installmentScheduleLocalList);
// installmentScheduleResponse.setAgreementNo("");
// }
else {
scheduleResponse = installmentScheduleResponse;
TextView agreementNumber = (TextView) activity.findViewById(R.id.agreementNumber);
agreementNumber.setText(installmentScheduleResponse.getAgreementNo());
TableLayout table = (TableLayout) activity.findViewById(R.id.tableHeaders);
int index = 1;
if(installmentScheduleResponse.getInstallmentScheduleList().size()==0){
NiftyDialogBuilder.getInstance(activity)
.withMessage(R.string.no_data_from_server)
.withTitle(context.getString(R.string.info_capital))
.withButton1Text(context.getString(R.string.btnClose))
.setButton1Click(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
})
.show();
}
for (InstallmentSchedule item : installmentScheduleResponse.getInstallmentScheduleList()) {
View row = LayoutInflater.from(context).inflate(R.layout.view_row_installment_schedule, table, false);
TextView no = (TextView) row.findViewById(R.id.no);
TextView dueDate = (TextView) row.findViewById(R.id.dueDate);
TextView amountInstallment = (TextView) row.findViewById(R.id.amountInstallment);
TextView amountPaid = (TextView) row.findViewById(R.id.amountPaid);
/*InstallmentScheduleItem installmentScheduleItem = new InstallmentScheduleItem();
installmentScheduleItem.setAgreementNo(item.getAgreement_no());
installmentScheduleItem.setBranchCode(item.getBranch_code());
installmentScheduleItem.setDtmCrt(item.getDtm_crt());
installmentScheduleItem.setDueDate(item.getDue_date());
installmentScheduleItem.setInstallmentAmount(item.getInstallment_amount());
installmentScheduleItem.setInstallmentNo(item.getInstallment_no());
installmentScheduleItem.setInterestAmound(item.getInterest_amound());
installmentScheduleItem.setLcAdminFee(item.getLc_admin_fee());
installmentScheduleItem.setLcAdminFeePaid(item.getLc_admin_fee_paid());
installmentScheduleItem.setLcAdminFeeWaive(item.getLc_admin_fee_waive());
installmentScheduleItem.setLcDays(item.getLc_days());
installmentScheduleItem.setLcInstlAmount(item.getLc_instl_amount());
installmentScheduleItem.setLcInstlPaid(item.getLc_instl_paid());
installmentScheduleItem.setLcInstlWaived(item.getLc_instl_waived());
installmentScheduleItem.setOsInterestAmount(item.getOs_interest_amount());
installmentScheduleItem.setOsPrincipalAmount(item.getOs_principal_amount());
installmentScheduleItem.setPrincipalAmount(item.getPrincipal_amount());
installmentScheduleItem.setUsrCrt(item.getUsr_crt());
installmentScheduleItem.setUuidTaskId(item.getUuid_task_h());*/
//row.setTag(item);
row.setTag(item);
no.setText(String.valueOf(index++));
dueDate.setText(Formatter.formatDate(item.getDue_date(), Global.DATE_STR_FORMAT));
amountInstallment.setText(item.getInstallment_amount());
amountPaid.setText(item.getInstallment_paid_amount());
String amtIns = item.getInstallment_amount();
if(amtIns!=null && amtIns.length()>3){
String part1 = amtIns.substring(amtIns.length()-3);
if(part1.substring(0, 1).equals("."))
{
amountInstallment.setGravity(Gravity.RIGHT);
}
}
String amtPaid = item.getInstallment_paid_amount();
if(amtPaid!=null && amtPaid.length()>3){
String part2 = amtPaid.substring(amtPaid.length()-3);
if(part2.substring(0, 1).equals("."))
{
amountPaid.setGravity(Gravity.RIGHT);
}
}
if (index % 2 == 1) {
row.setBackgroundResource(R.color.tv_gray_light);
} else if (index % 2 == 0) {
row.setBackgroundResource(R.color.tv_gray);
}
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
detailInstallmentSchedule = (InstallmentSchedule) v.getTag();
Intent intent = new Intent(context, InstallmentScheduleDetailFragment.class);
// intent.putExtra(InstallmentScheduleDetailFragment.INSTALLMENT_SCHEDULE_DETAIL, detail);
activity.startActivity(intent);
}
});
table.addView(row);
}
}
}
}.execute();
}
}

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_press" />
<item android:state_enabled="false" android:drawable="@drawable/btn_press" />
<item android:drawable="@drawable/btn_unpress" />
</selector>

View file

@ -0,0 +1,85 @@
package com.services;
import android.app.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import androidx.core.app.NotificationCompat;
import com.adins.mss.foundation.security.storepreferences.ObscuredSharedPreferences;
import com.adins.mss.odr.R;
public class MOApplicationRunningService extends Service {
public MOApplicationRunningService() {}
public void onCreate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(getPackageName(), getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("App Service Persistent");
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
ObscuredSharedPreferences sharedPref = ObscuredSharedPreferences.getPrefs(this,
"GlobalData", Context.MODE_PRIVATE);
if (sharedPref.contains("HAS_LOGGED")) {
Notification notification = new NotificationCompat.Builder(this, getPackageName())
.setSmallIcon(R.drawable.icon_notif_new)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.application_is_running))
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setOngoing(true)
.build();
startForeground(2043, notification);
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onTaskRemoved(Intent rootIntent){
String manufacture = Build.MANUFACTURER.toLowerCase();
ObscuredSharedPreferences sharedPref = ObscuredSharedPreferences.getPrefs(getApplicationContext(),
"GlobalData", Context.MODE_PRIVATE);
boolean hasLogged = sharedPref.getBoolean("HAS_LOGGED", false);
if (hasLogged) {
switch (manufacture) {
case "oppo":
case "vivo":
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
break;
default:
break;
}
}
super.onTaskRemoved(rootIntent);
}
public static class UserLogoutReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent locationTrackingService = new Intent(context, MOApplicationRunningService.class);
context.stopService(locationTrackingService);
}
}
}

View file

@ -0,0 +1,383 @@
package com.adins.mss.odr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import com.adins.mss.base.GlobalData;
import com.adins.mss.base.util.GsonHelper;
import com.adins.mss.base.util.Utility;
import com.adins.mss.constant.Global;
import com.adins.mss.foundation.dialog.DialogManager;
import com.adins.mss.foundation.dialog.NiftyDialogBuilder;
import com.adins.mss.foundation.formatter.Formatter;
import com.adins.mss.foundation.formatter.Tool;
import com.adins.mss.foundation.http.HttpConnectionResult;
import com.adins.mss.foundation.http.HttpCryptedConnection;
import com.adins.mss.odr.model.JsonRequestCheckOrder;
import com.adins.mss.odr.model.JsonResponseServer;
import com.adins.mss.odr.model.JsonResponseServer.ResponseServer;
import com.google.firebase.perf.FirebasePerformance;
import com.google.firebase.perf.metrics.HttpMetric;
import org.acra.ACRA;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import static com.adins.mss.odr.CheckOrderActivity.keyCustName;
/**
* Created by winy.firdasari on 20/01/2015.
*/
public class ResultOrderActivity extends Activity {
private static String url = GlobalData.getSharedGlobalData().getURL_CHECKORDER();
protected String getUsedURL(){
return GlobalData.getSharedGlobalData().getURL_CHECKORDER();
}
ExpandableListAdapter listAdapter;
protected ExpandableListView expListView;
protected List<String> listDataHeader;
protected HashMap<String, List<String>> listDataChild;
protected String startDate;
protected String endDate;
protected String orderNumber;
protected String flag;
private String custName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ACRA.getErrorReporter().putCustomData("LAST_CLASS_ACCESSED", getClass().getSimpleName());
setContentView(R.layout.result_order_layout);
initialize();
new ResultOrderTask().execute();
}
protected void initialize() {
// TODO Auto-generated method stub
Intent i = getIntent();
// Receiving the Data
String mStartDate = i.getStringExtra("startDate");
String mEndDate = i.getStringExtra("endDate");
String mNomorOrder = i.getStringExtra("nomorOrder");
String mCustName = i.getStringExtra(keyCustName);
String newflag = i.getStringExtra("flag");
ResultOrderActivity.url = getUsedURL();
//jika memilih order by No Order
if(null != mNomorOrder && !mNomorOrder.equalsIgnoreCase("")){
orderNumber=mNomorOrder;
flag=Global.FLAG_BY_ORDERNUMBER;
}
//jika memilih order by date
else if (null != mStartDate && !mStartDate.equalsIgnoreCase("")) {
startDate = mStartDate;
endDate = mEndDate;
flag = Global.FLAG_BY_DATE;
} else if (null != mCustName && !mCustName.equalsIgnoreCase("")) {
custName = mCustName;
flag = Global.FLAG_BY_CUSTOMER_NAME;
}
if(newflag!=null){
flag = newflag;
}
if ("orderTracking".equalsIgnoreCase(flag)) {
startDate = "1";
endDate = "1";
orderNumber = "1";
custName = "1";
}
expListView = (ExpandableListView) findViewById(R.id.resultOrderlist);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " " + getString(R.string.expanded),
Toast.LENGTH_SHORT);
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " " + getString(R.string.collapsed),
Toast.LENGTH_SHORT);
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT);
return false;
}
});
}
public String getDataFromURL(String url) throws IOException {
String resp = null;
try {
List<NameValuePair> param = generateRequestParam();
JsonRequestCheckOrder requestCheckOrder = new JsonRequestCheckOrder();
requestCheckOrder.setAudit(GlobalData.getSharedGlobalData().getAuditData());
// requestCheckOrder.addItemToUnstructured(new KeyValue("imei", GlobalData.getSharedGlobalData().getImei()), false);
if(param.get(3).getValue().equals(Global.FLAG_BY_DATE)){
requestCheckOrder.setStartDate(param.get(0).getValue());
requestCheckOrder.setEndDate(param.get(1).getValue());
}
else if(param.get(3).getValue().equals(Global.FLAG_BY_ORDERNUMBER)){
requestCheckOrder.setOrderNumber(param.get(2).getValue());
}
else if (null != custName && !custName.equalsIgnoreCase("")) {
requestCheckOrder.setCustomerName(custName);
}
else if(param.get(3).getValue().equals(Global.FLAG_FOR_CANCELORDER)){
if(param.get(2).getValue().equals("1")){
requestCheckOrder.setStartDate(param.get(0).getValue());
requestCheckOrder.setEndDate(param.get(1).getValue());
}else{
requestCheckOrder.setOrderNumber(param.get(2).getValue());
}
// requestCheckOrder.setFlag(param.get(3).getValue());
// requestCheckOrder.setStatus(param.get(4).getValue());
}
else if(param.get(3).getValue().equals(Global.FLAG_FOR_ORDERREASSIGNMENT)){
if(param.get(2).getValue().equals("1")){
requestCheckOrder.setStartDate(param.get(0).getValue());
requestCheckOrder.setEndDate(param.get(1).getValue());
}else{
requestCheckOrder.setOrderNumber(param.get(2).getValue());
}
requestCheckOrder.setFlag(param.get(3).getValue());
}
String json = GsonHelper.toJson(requestCheckOrder);
boolean encrypt = GlobalData.getSharedGlobalData().isEncrypt();
boolean decrypt = GlobalData.getSharedGlobalData().isDecrypt();
HttpCryptedConnection httpConn = new HttpCryptedConnection(ResultOrderActivity.this, encrypt, decrypt);
HttpConnectionResult serverResult = null;
//Firebase Performance Trace HTTP Request
HttpMetric networkMetric =
FirebasePerformance.getInstance().newHttpMetric(url, FirebasePerformance.HttpMethod.POST);
Utility.metricStart(networkMetric, json);
try {
serverResult = httpConn.requestToServer(url, json);
Utility.metricStop(networkMetric, serverResult);
} catch (Exception e) {
e.printStackTrace();
}
if (null != serverResult && serverResult.isOK()) {
resp = serverResult.getResult();
}
}catch (Exception e) {
resp=e.getMessage();
}
return resp;
}
protected List<NameValuePair> generateRequestParam() throws ParseException {
String sdtSDate = "1";
String sdtEDate = "1";
if(startDate==null||endDate==null||"".equalsIgnoreCase(startDate)||"".equalsIgnoreCase(endDate)
||"1".equalsIgnoreCase(startDate)||"1".equalsIgnoreCase(endDate)){
}else{
//convert format date biar bisa di tranlate di DB servernya
SimpleDateFormat f = new SimpleDateFormat(Global.DATE_STR_FORMAT);
Date sDate,eDate;
sDate = f.parse(startDate);
eDate = f.parse(endDate);
sdtSDate = Formatter.formatDate(sDate, Global.DATE_STR_FORMAT_GSON);
sdtEDate = Formatter.formatDate(eDate, Global.DATE_STR_FORMAT_GSON);
}
List<NameValuePair> param = new ArrayList<NameValuePair>();
// String userId = ApplicationBean.getInstance().getUserId();
param.add(new BasicNameValuePair("startdate", sdtSDate));
param.add(new BasicNameValuePair("enddate", sdtEDate));
param.add(new BasicNameValuePair("ordernumber", orderNumber));
param.add(new BasicNameValuePair("flag", flag));
// param.add(new BasicNameValuePair("userid", userId ));
return param;
}
protected void processServerResponse(String result) {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
try {
JsonResponseServer resultOrder = GsonHelper.fromJson(result, JsonResponseServer.class);
List<ResponseServer> responseServers = resultOrder.getListResponseServer();
if(responseServers!=null&&responseServers.size()>0){
for(int i=0;i<resultOrder.getListResponseServer().size();i++){
ResponseServer responseServer = responseServers.get(i);
String orderNo = responseServer.getKey();
String customerName = responseServer.getValue();
listDataHeader.add(orderNo+" - "+customerName);
List<ResponseServer> SubResultOrder = responseServer.getSubListResponseServer();
List<String> statusOrder = new ArrayList<String>();
for(int ii = 0; ii < SubResultOrder.size(); ii++){
ResponseServer subResponseServer = SubResultOrder.get(ii);
statusOrder.add(subResponseServer.getValue());
}
listDataChild.put(listDataHeader.get(i), statusOrder);
listAdapter = new ExpandableListAdapter(ResultOrderActivity.this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
}
}else{
String message;
if(resultOrder.getStatus().getMessage()!=null){
message = getString(R.string.data_not_found)+" " +resultOrder.getStatus().getMessage();
}else{
message = getString(R.string.data_not_found);
}
final NiftyDialogBuilder builder = NiftyDialogBuilder.getInstance(this);
builder.withTitle(getString(R.string.info_capital))
.withMessage(message)
.withButton1Text(getString(R.string.btnOk))
.isCancelable(false)
.setButton1Click(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
builder.dismiss();
finish();
}
}).show();
}
} catch (Exception e) {
System.out.println(e);
final NiftyDialogBuilder builder = NiftyDialogBuilder.getInstance(this);
builder.withTitle(getString(R.string.info_capital))
.withMessage(getApplicationContext().getString(R.string.request_error))
.withButton1Text(getString(R.string.btnOk))
.setButton1Click(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
builder.dismiss();
finish();
}
}).show();
}
}
private class ResultOrderTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String errMessage = null;
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ResultOrderActivity.this,
"", getString(R.string.progressWait), true);
}
@Override
protected String doInBackground(String... arg0) {
String result = null;
if(Tool.isInternetconnected(getApplicationContext())){
try {
result = ResultOrderActivity.this.getDataFromURL(url);
} catch (IOException ioe) {
// TODO Auto-generated catch block
ioe.printStackTrace();
try {
progressDialog.dismiss();
} catch (Exception e) {}
errMessage = ioe.getMessage();
}
}else{
result = getString(R.string.no_internet_connection);
}
return result;
}
@Override
protected void onPostExecute(String result) {
if (progressDialog!=null&&progressDialog.isShowing()){
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
if(GlobalData.isRequireRelogin()){
return;
}
if(null != result) {
if (getString(R.string.no_internet_connection).equals(result)) {
NiftyDialogBuilder builder = NiftyDialogBuilder.getInstance(ResultOrderActivity.this);
builder.withTitle(getString(R.string.info_capital))
.withMessage(getString(R.string.no_internet_connection))
.show();
} else {
processServerResponse(result);
}
}
}
}
}

View file

@ -0,0 +1,110 @@
package com.adins.mss.coll.fragments;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TextView;
import com.adins.mss.coll.R;
import com.adins.mss.coll.models.InstallmentScheduleItem;
import com.adins.mss.constant.Global;
import com.adins.mss.dao.InstallmentSchedule;
import com.adins.mss.foundation.formatter.Formatter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import org.acra.ACRA;
/**
* Created by aditya on 07/05/15.
*/
public class InstallmentScheduleDetailFragment extends AppCompatActivity {
public static final String INSTALLMENT_SCHEDULE_DETAIL = "InstallmentScheduleDetailFragment.INSTALLMENT_SCHEDULE_DETAIL";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_fragment_collection_activity_detail);
ACRA.getErrorReporter().putCustomData("LAST_CLASS_ACCESSED", getClass().getSimpleName());
TableLayout table = (TableLayout) findViewById(R.id.tableCollectionDetail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.title_mn_installmentscheduledet));
toolbar.setTitleTextColor(getResources().getColor(com.adins.mss.base.R.color.fontColorWhite));
setSupportActionBar(toolbar);
InstallmentSchedule item = InstallmentScheduleFragment.detailInstallmentSchedule;
int index = 1;
Class<InstallmentSchedule> type = InstallmentSchedule.class;
for (Method method : type.getMethods()) {
if (!method.getName().startsWith("get")) {
continue;
}
// Seriously? No one want to output the class name for non techies.
if (method.getName().equals("getClass")) {
continue;
}
View row = LayoutInflater.from(this).inflate(
R.layout.view_no_label_value, table, false);
TextView no = (TextView) row.findViewById(R.id.no);
TextView label = (TextView) row.findViewById(R.id.fieldName);
TextView value = (TextView) row.findViewById(R.id.fieldValue);
String labelField = method.getName().replaceFirst("get", "");
if (labelField.equalsIgnoreCase("Dtm_crt")
|| labelField.equalsIgnoreCase("Usr_crt")
|| labelField.equalsIgnoreCase("Uuid_installment_schedule")
|| labelField.equalsIgnoreCase("Uuid_task_h")
|| labelField.equalsIgnoreCase("branch_code")) {
} else {
no.setText(String.valueOf(index++));
label.setText(labelField.replace("_", " "));
label.setGravity(Gravity.LEFT);
try {
String stringValue = "";
Object itemValue = method.invoke(item);
if (itemValue == null) {
stringValue = "-";
} else if (method.getReturnType() == Date.class) {
stringValue = Formatter.formatDate((Date) itemValue,
Global.DATE_STR_FORMAT);
} else {
stringValue = String.valueOf(itemValue);
}
// if(stringValue!=null && stringValue.length()>3){
// String part1 = stringValue.substring(stringValue.length()-3);
// if(part1.substring(0, 1).equals("."))
// {
// value.setGravity(Gravity.RIGHT);
// }
// }
value.setText(stringValue);
value.setGravity(Gravity.RIGHT);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// if (index % 2 == 1) {
// row.setBackgroundResource(R.color.tv_gray_light);
// } else if (index % 2 == 0) {
// row.setBackgroundResource(R.color.tv_gray);
// }
table.addView(row);
}
}
}
}

View file

@ -0,0 +1,54 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/gradient_end</item>
</style>
<style name="Widget" />
<style name="Widget.ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse" />
<style name="Widget.Light" />
<style name="Widget.Light.ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar.Solid" />
<style name="Widget.ActionBar.Transparent">
<item name="android:background">@android:color/transparent</item>
</style>
<style name="Widget.Light.ActionBar.Transparent">
<item name="android:background">@android:color/transparent</item>
</style>
<style name="PageTextTitle" parent="android:TextAppearance.DeviceDefault.Small">
<item name="android:textColor">@color/fontColorWhite</item>
<item name="android:textStyle">bold</item>
</style>
<style name="FieldLabel" parent="android:TextAppearance.DeviceDefault.Small">
<item name="android:textColor">@color/gradient_end</item>
</style>
<style name="ButtonSmooth" parent="android:Widget.Holo.Light.Button">
<item name="android:background">@color/gradient_start</item>
<item name="android:textColor">#FFF</item>
</style>
<style name="SmallButtonSmooth" parent="ButtonSmooth">
<item name="android:textSize">14sp</item>
</style>
<style name="AppTheme.NoTitle" parent="AppTheme">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
<style name="DashboardCollTabText" parent="TextAppearance.Design.Tab">
<item name="android:textSize">13sp</item>
</style>
</resources>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View file

@ -0,0 +1,792 @@
package com.adins.mss.foundation.http;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.adins.mss.base.AppContext;
import com.adins.mss.base.GlobalData;
import com.adins.mss.base.R;
import com.adins.mss.base.crashlytics.FireCrash;
import com.adins.mss.base.login.DefaultLoginModel;
import com.adins.mss.base.util.GsonHelper;
import com.adins.mss.base.util.UserSession;
import com.adins.mss.base.util.Utility;
import com.adins.mss.constant.Global;
import com.adins.mss.foundation.dialog.DialogManager;
import com.adins.mss.foundation.formatter.Tool;
import com.adins.mss.foundation.http.net.HttpClient;
import com.adins.mss.foundation.http.net.HttpsClient;
import com.adins.mss.foundation.oauth2.OAuthConstants;
import com.adins.mss.foundation.oauth2.OAuthUtils;
import com.adins.mss.foundation.oauth2.OauthErrorResponse;
import com.adins.mss.foundation.oauth2.Token;
import com.adins.mss.foundation.oauth2.store.SharedPreferencesTokenStore;
import com.adins.mss.foundation.security.storepreferences.ObscuredSharedPreferences;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.services.NotificationThread;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
/**
* @author glen.iglesias
* <p>
* A Class to do HTTP Connection with POST Method, and use encryption via ConnectionCryptor interface
*/
public class HttpConnection {
public static final String HEADER_CONTENT_TYPE_KEY = "Content-Type";
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
public static final String HEADER_TENANT = "Tenant";
public static final String HEADER_CONTENT_TYPE_URL_ENCODED = "application/x-www-form-urlencoded";
public static final String HEADER_CONTENT_TYPE_PDF = "application/pdf";
public static final int FLAG_LOGOUT_STATUS_CODE = 1158;
public static final int FLAG_UNINSTALL_STATUS_CODE = 1153;
public static final String ERROR_STATUSCODE_FROM_SERVER = "Your account can not use this application further";
public static String tenantId;
/**
* To dictate if outgoing data need to be encrypted
*/
private boolean enableEncryption;
/**
* To dictate if received data need to be decrypted
*/
private boolean enableDecryption;
private ConnectionCryptor cryptor;
private int defaultConnectionTimeout = 120000;
private Context mContext;
private boolean isErrorFromServer = false;
private boolean isSecureConnection;
private Activity mActivity;
public HttpConnection() {
}
public HttpConnection(boolean encrypt, boolean decrypt) {
this.enableEncryption = encrypt;
this.enableDecryption = decrypt;
}
public HttpConnection(Context context, boolean encrypt, boolean decrypt, boolean isSecureConnection) {
this.enableEncryption = encrypt;
this.enableDecryption = decrypt;
this.mContext = context;
this.isSecureConnection = isSecureConnection;
}
public HttpConnection(Context context, boolean encrypt, boolean decrypt) {
this.enableEncryption = encrypt;
this.enableDecryption = decrypt;
this.mContext = context;
this.isSecureConnection = GlobalData.getSharedGlobalData().isSecureConnection();
}
public HttpConnection(boolean encrypt, boolean decrypt, ConnectionCryptor cryptor) {
this(encrypt, decrypt);
}
/**
* A static method to check if internet connection is available
* <p>Snippet from : <br>http://stackoverflow.com/questions/9570237/android-check-internet-connection
*
* @return true if it is connected, false if it is not
*/
public static boolean isInternetConnectedTo() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
return ipAddr != null;
} catch (Exception e) {
FireCrash.log(e);
return false;
}
}
public Activity getActivity() {
return mActivity;
}
public void setActivity(Activity mActivity) {
this.mActivity = mActivity;
}
//=== Properties ===//
public boolean isEnableEncryption() {
return enableEncryption;
}
public void setEnableEncryption(boolean enableEncryption) {
this.enableEncryption = enableEncryption;
}
public Context getContext() {
return mContext;
}
public void setContext(Context mContext) {
this.mContext = mContext;
}
public boolean isSecureConnection() {
return isSecureConnection;
}
public void setSecureConnection(boolean isSecureConnection) {
this.isSecureConnection = isSecureConnection;
}
public boolean isEnableDecryption() {
return enableDecryption;
}
public void setEnableDecryption(boolean enableDecryption) {
this.enableDecryption = enableDecryption;
}
public ConnectionCryptor getCryptor() {
return cryptor;
}
public void setCryptor(ConnectionCryptor cryptor) {
this.cryptor = cryptor;
}
public int getDefaultConnectionTimeout() {
return defaultConnectionTimeout;
}
public void setDefaultConnectionTimeout(int defaultConnectionTimeout) {
this.defaultConnectionTimeout = defaultConnectionTimeout;
}
public boolean isHaveTenant(String loginId) {
String[] idNtenant = Tool.split(loginId, "@");
return idNtenant.length > 1;
}
//=== Methods ===//
public String getTenantId() {
if (tenantId == null || tenantId.isEmpty()) {
String loginId = GlobalData.getSharedGlobalData().getUser().getLogin_id();
String[] idNtenant = Tool.split(loginId, "@");
if (idNtenant.length > 1)
tenantId = idNtenant[1];
}
return tenantId;
}
/**
* Method to make a HTTP POST request to server, returning HttpConnectionResult data model
* <p>
* <p>NOTE: need to run in background thread
*
* @param url target url to make HTTP Connection
* @param data content to send to target url
* @param connectionTimeout
* @return HttpConnectionResult object, containing returned status code, error message (if any), and returned message from server (if succeed)
*/
public HttpConnectionResult requestHTTPPost(String url, String data, int connectionTimeout) throws Exception {
HttpConnectionResult result = null;
GlobalData.setRequireRelogin(false);
try {
HttpClient client = new HttpClient(mContext);
client.setConnectionTimeout((long) connectionTimeout);
if (enableEncryption) {
data = cryptor.encrpyt(data);
}
RequestBody body = RequestBody.create(MediaType.parse(HEADER_CONTENT_TYPE_KEY), data);
Request.Builder builder = new Request.Builder();
builder.url(url)
.addHeader(HEADER_CONTENT_TYPE_KEY, HEADER_CONTENT_TYPE_URL_ENCODED);
if (GlobalData.getSharedGlobalData().isRequiresAccessToken()) {
if (GlobalData.getSharedGlobalData().getToken().isExpired()) {
Token token = GlobalData.getSharedGlobalData().getToken().refresh(getActivity(), GlobalData.getSharedGlobalData().getoAuth2Client());
SharedPreferencesTokenStore tokenStore = new SharedPreferencesTokenStore(mContext);
tokenStore.store(GlobalData.getSharedGlobalData().getoAuth2Client().getUsername(), token);
GlobalData.getSharedGlobalData().setToken(token);
}
builder.addHeader(OAuthConstants.AUTHORIZATION,
OAuthUtils.getAuthorizationHeaderForAccessToken(
GlobalData.getSharedGlobalData().getToken().getAccessToken()));
if (GlobalData.getSharedGlobalData().getUser() != null) {
if (isHaveTenant(GlobalData.getSharedGlobalData().getUser().getLogin_id()))
builder.addHeader(HEADER_TENANT, getTenantId());
} else if (DefaultLoginModel.tenantId != null && !DefaultLoginModel.tenantId.isEmpty()) {
builder.addHeader(HEADER_TENANT, DefaultLoginModel.tenantId);
}
}
builder.post(body);
Request request = builder.build();
Response responsePost = null;
try {
responsePost = client.execute(request);
int statusCode = responsePost.code();
if (responsePost.priorResponse() != null && responsePost.priorResponse().code() != HttpStatus.SC_OK) {
result = new HttpConnectionResult(null, responsePost.priorResponse().message());
return result;
}
if (statusCode == HttpStatus.SC_OK) {
String strResult = null;
InputStream in = responsePost.body().byteStream();
strResult = IOUtils.toString(in, Charset.defaultCharset());
if (enableDecryption) {
strResult = cryptor.decrypt(strResult);
}
try {
MssResponseType mss = GsonHelper.fromJson(strResult, MssResponseType.class);
if (mss != null) {
int code = mss.getStatus().getCode();
if (code == FLAG_LOGOUT_STATUS_CODE) {
if (getContext() != null) {
isErrorFromServer = false;
GlobalData.setRequireRelogin(true);
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
try {
Intent intent = new Intent(Global.FORCE_LOGOUT_ACTION);
LocalBroadcastManager.getInstance(AppContext.getAppContext()).sendBroadcast(intent);
if (mContext != null) {
DialogManager.showForceExitAlert(mContext, mContext.getString(R.string.msgLogout));
}
} catch (Exception e) {
FireCrash.log(e);
}
}
});
} else if (code == FLAG_UNINSTALL_STATUS_CODE) {
if (getActivity() != null) {
isErrorFromServer = true;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
try {
if (getActivity() != null) {
DialogManager.UninstallerHandler(getActivity());
}
} catch (Exception e) {
FireCrash.log(e);
}
}
});
}
com.adins.mss.foundation.notification.Notification.getSharedNotification().clearNotif(mContext, 9);
}
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
if (mContext != null) {
if (mActivity != null && !mActivity.isFinishing()) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(NotificationThread.getNotificationIcon());
NotificationCompat.BigTextStyle inboxStyle =
new NotificationCompat.BigTextStyle();
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle(mContext.getString(R.string.no_internet_connection));
inboxStyle.bigText(mContext.getString(R.string.connection_failed));
inboxStyle.setSummaryText(mContext.getString(R.string.connection_failed_wifi));
builder.setPriority(Thread.NORM_PRIORITY);
builder.setContentTitle(mContext.getString(R.string.no_internet_connection));
builder.setContentText(mContext.getString(R.string.connection_failed));
builder.setSubText(mContext.getString(R.string.connection_failed_wifi));
builder.setDefaults(Notification.DEFAULT_VIBRATE);
builder.setStyle(inboxStyle);
builder.setAutoCancel(true);
mNotificationManager.notify(9, builder.build());
}
});
}
}
} catch (JsonParseException jpe) {
jpe.printStackTrace();
} catch (IllegalStateException ise) {
ise.printStackTrace();
} catch (Exception e) {
FireCrash.log(e);
e.printStackTrace();
}
//generate result
if (isErrorFromServer) {
result = new HttpConnectionResult(null, ERROR_STATUSCODE_FROM_SERVER);
} else {
result = new HttpConnectionResult(statusCode, responsePost.message(), strResult);
}
} else if (statusCode == OAuthConstants.HTTP_BAD_REQUEST || statusCode == OAuthConstants.HTTP_UNAUTHORIZED) {
OauthErrorResponse errorResponse = null;
try {
errorResponse = GsonHelper.fromJson(responsePost.body().string(), OauthErrorResponse.class);
result = new HttpConnectionResult(statusCode, responsePost.message(), errorResponse.error_description);
} catch (IOException e) {
e.printStackTrace();
result = new HttpConnectionResult(statusCode, responsePost.message(), responsePost.message());
}
if (statusCode == OAuthConstants.HTTP_UNAUTHORIZED) {
onInvalidToken();
}
} else {
//generate failed result
result = new HttpConnectionResult(statusCode, responsePost.message(), responsePost.message());
}
}
catch (UnknownHostException e){
FireCrash.log(e);
String msg = null;
if(mContext != null)
msg = mContext.getString(R.string.no_internet_connection);
else if(mActivity != null)
msg = mActivity.getString(R.string.no_internet_connection);
result = new HttpConnectionResult(null, msg);
return result;
}
catch (SocketTimeoutException e) {
FireCrash.log(e);
String msg = null;
if(mContext != null)
msg = mContext.getString(R.string.connection_timeout);
else if(mActivity != null)
msg = mActivity.getString(R.string.connection_timeout);
result = new HttpConnectionResult(null, msg);
return result;
}
catch (Exception e) {
FireCrash.log(e);
String msg;
msg = e.getMessage();
if (msg == null) msg = e.getClass().getName();
result = new HttpConnectionResult(null, msg);
return result;
} finally {
if (responsePost != null) {
try {
responsePost.body().close();
} catch (Exception e) {
FireCrash.log(e);
e.printStackTrace();
}
}
}
} catch (InvalidTokenException e) {
onInvalidToken();
} catch (Exception e) {
FireCrash.log(e);
String msg;
msg = e.getMessage();
if (msg == null)
msg = e.getClass().getName();
result = new HttpConnectionResult(null, msg);
}
return result;
}
/**
* Method to make a HTTPS POST request to server, returning HttpConnectionResult data model
* <p>
* <p>NOTE: need to run in background thread
*
* @param url target url to make HTTP Connection
* @param data content to send to target url
* @param connectionTimeout connection time out in milisecond
* @return HttpConnectionResult object, containing returned status code, error message (if any), and returned message from server (if succeed)
*/
public HttpConnectionResult requestHTTPSPost(String url, String data, int connectionTimeout) throws Exception {
HttpConnectionResult result = null;
try {
HttpsClient client = new HttpsClient(mContext);
client.setAcceptAllCertificate(true);
client.setBypassHostnameVerification(true);
client.setConnectionTimeout((long) connectionTimeout);
client.initialize();
if (enableEncryption) {
data = cryptor.encrpyt(data);
}
RequestBody body = RequestBody.create(MediaType.parse(HEADER_CONTENT_TYPE_KEY), data);
Request.Builder builder = new Request.Builder();
builder.url(url)
.addHeader(HEADER_CONTENT_TYPE_KEY, HEADER_CONTENT_TYPE_URL_ENCODED);
if (GlobalData.getSharedGlobalData().isRequiresAccessToken()) {
if (GlobalData.getSharedGlobalData().getToken() != null &&
GlobalData.getSharedGlobalData().getToken().isExpired()) {
Token token = GlobalData.getSharedGlobalData().getToken().refresh(getActivity(), GlobalData.getSharedGlobalData().getoAuth2Client());
SharedPreferencesTokenStore tokenStore = new SharedPreferencesTokenStore(mContext);
tokenStore.store(GlobalData.getSharedGlobalData().getoAuth2Client().getUsername(), token);
GlobalData.getSharedGlobalData().setToken(token);
}
builder.addHeader(OAuthConstants.AUTHORIZATION,
OAuthUtils.getAuthorizationHeaderForAccessToken(
GlobalData.getSharedGlobalData().getToken().getAccessToken()));
if (GlobalData.getSharedGlobalData().getUser() != null) {
if (isHaveTenant(GlobalData.getSharedGlobalData().getUser().getLogin_id()))
builder.addHeader(HEADER_TENANT, getTenantId());
} else if (DefaultLoginModel.tenantId != null && !DefaultLoginModel.tenantId.isEmpty()) {
builder.addHeader(HEADER_TENANT, DefaultLoginModel.tenantId);
}
}
builder.post(body);
Request request = builder.build();
Response responsePost = null;
try {
responsePost = client.execute(request);
int statusCode = responsePost.code();
if (responsePost.priorResponse() != null && responsePost.priorResponse().code() != HttpStatus.SC_OK) {
result = new HttpConnectionResult(null, responsePost.priorResponse().message());
return result;
}
if (statusCode == HttpStatus.SC_OK) {
String strResult = null;
InputStream in = responsePost.body().byteStream();
strResult = IOUtils.toString(in, Charset.defaultCharset());
if (enableDecryption) {
strResult = cryptor.decrypt(strResult);
}
try {
MssResponseType mss = GsonHelper.fromJson(strResult, MssResponseType.class);
if (mss != null) {
int code = mss.getStatus().getCode();
if (code == FLAG_LOGOUT_STATUS_CODE) {
if (getActivity() != null) {
isErrorFromServer = false;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
try {
if (getActivity() != null) {
DialogManager.showForceExitAlert(getActivity(), mContext.getString(R.string.msgLogout));
}
} catch (Exception e) {
FireCrash.log(e);
}
}
});
} else if (code == FLAG_UNINSTALL_STATUS_CODE) {
if (getActivity() != null) {
isErrorFromServer = true;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
try {
if (getActivity() != null) {
DialogManager.UninstallerHandler(getActivity());
}
} catch (Exception e) {
FireCrash.log(e);
}
}
});
}
}
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
if (mContext != null) {
if (mActivity != null && !mActivity.isFinishing()) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(NotificationThread.getNotificationIcon());
NotificationCompat.BigTextStyle inboxStyle =
new NotificationCompat.BigTextStyle();
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle(mContext.getString(R.string.no_internet_connection));
inboxStyle.bigText(mContext.getString(R.string.connection_failed));
inboxStyle.setSummaryText(mContext.getString(R.string.connection_failed_wifi));
builder.setPriority(Thread.NORM_PRIORITY);
builder.setContentTitle(mContext.getString(R.string.no_internet_connection));
builder.setContentText(mContext.getString(R.string.connection_failed));
builder.setSubText(mContext.getString(R.string.connection_failed_wifi));
builder.setDefaults(Notification.DEFAULT_VIBRATE);
builder.setStyle(inboxStyle);
builder.setAutoCancel(true);
mNotificationManager.notify(9, builder.build());
}
});
}
}
} catch (JsonParseException jpe) {
jpe.printStackTrace();
} catch (IllegalStateException ise) {
ise.printStackTrace();
} catch (Exception e) {
FireCrash.log(e);
e.printStackTrace();
}
//generate result
if (isErrorFromServer) {
result = new HttpConnectionResult(null, ERROR_STATUSCODE_FROM_SERVER);
} else {
result = new HttpConnectionResult(statusCode, responsePost.message(), strResult);
}
} else if (statusCode == OAuthConstants.HTTP_BAD_REQUEST || statusCode == OAuthConstants.HTTP_UNAUTHORIZED) {
OauthErrorResponse errorResponse = null;
try {
errorResponse = GsonHelper.fromJson(responsePost.body().string(), OauthErrorResponse.class);
result = new HttpConnectionResult(statusCode, responsePost.message(), errorResponse.error_description);
} catch (IOException e) {
e.printStackTrace();
result = new HttpConnectionResult(statusCode, responsePost.message(), responsePost.message());
}
if (statusCode == OAuthConstants.HTTP_UNAUTHORIZED) {
onInvalidToken();
}
} else {
//generate failed result
result = new HttpConnectionResult(statusCode, responsePost.message(), responsePost.message());
}
}
catch (UnknownHostException e){
FireCrash.log(e);
String msg = null;
if(mContext != null)
msg = mContext.getString(R.string.no_internet_connection);
else if(mActivity != null)
msg = mActivity.getString(R.string.no_internet_connection);
result = new HttpConnectionResult(null, msg);
return result;
}
catch (SocketTimeoutException e) {
FireCrash.log(e);
String msg = null;
if(mContext != null)
msg = mContext.getString(R.string.connection_timeout);
else if(mActivity != null)
msg = mActivity.getString(R.string.connection_timeout);
result = new HttpConnectionResult(null, msg);
return result;
}
catch (Exception e) {
FireCrash.log(e);
String msg;
msg = e.getMessage();
if (msg == null) msg = e.getClass().getName();
result = new HttpConnectionResult(null, msg);
return result;
} finally {
if (responsePost != null) {
try {
responsePost.body().close();
} catch (Exception e) {
FireCrash.log(e);
e.printStackTrace();
}
}
}
} catch (InvalidTokenException e) {
onInvalidToken();
} catch (Exception e) {
FireCrash.log(e);
String msg;
msg = e.getMessage();
if (msg == null)
msg = e.getClass().getName();
else{
if(msg.contains("failed to connect to")){
if(mContext != null)
msg = mContext.getString(R.string.connection_timeout);
else if(mActivity != null)
msg = mActivity.getString(R.string.connection_timeout);
}
}
result = new HttpConnectionResult(null, msg);
}
return result;
}
/**
* A variation of requestHTTPPost which will throw Exception if connection failed
*
* @param url target url to make HTTP Connection
* @param data content to send to target url
* @param connectionTimeout
* @throws Exception if connection failed
* @return HttpConnectionResult object, containing returned status code, error message (if any), and returned message from server (if succeed)
*/
public HttpConnectionResult requestHTTPPost2(String url, String data, int connectionTimeout) throws Exception {
HttpConnectionResult result = requestHTTPPost(url, data, connectionTimeout);
if (result.getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Connection to server failed: " + result.getStatusCode() + " "
+ result.getReasonPhrase());
} else {
return result;
}
}
public HttpConnectionResult requestToServer(String url, String data, int connectionTimeout) throws Exception {
HttpConnectionResult result;
if (isSecureConnection) {
result = requestHTTPSPost(url, data, connectionTimeout);
} else {
result = requestHTTPPost(url, data, connectionTimeout);
}
return result;
}
public HttpConnectionResult requestToServer(String url, String data) throws Exception {
HttpConnectionResult result;
if (isSecureConnection) {
result = requestHTTPSPost(url, data, defaultConnectionTimeout);
} else {
result = requestHTTPPost(url, data, defaultConnectionTimeout);
}
return result;
}
/**
* Do a HTTP Request with POST Method and use default timeout
*
* @param url target url to make HTTP Connection
* @param data content to send to target url
* @return HttpConnectionResult object, containing returned status code, error message (if any), and returned message from server (if succeed)
*/
public HttpConnectionResult requestHTTPPost(String url, String data) throws Exception {
HttpConnectionResult result = requestHTTPPost(url, data, defaultConnectionTimeout);
return result;
}
/**
* Do a HTTP Request with POST Method and use default timeout, but throw exception if connection failed
*
* @param url target url to make HTTP Connection
* @param data content to send to target url
* @throws Exception if connection failed
* @return HttpConnectionResult object, containing returned status code, error message (if any), and returned message from server (if succeed)
*/
public HttpConnectionResult requestHTTPPost2(String url, String data) throws Exception {
HttpConnectionResult result = requestHTTPPost2(url, data, defaultConnectionTimeout);
return result;
}
/**
* Method to convert InputStream into readable String
*
* @param is InputStream to be converted
* @throws IOException
* @return Result of InputStream conversion
*/
public String inputStreamToString(InputStream is) throws IOException {
String result;
String line = null;
StringBuilder stringbuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((line = br.readLine()) != null)
stringbuilder.append(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
result = stringbuilder.toString();
return result;
}
private void onInvalidToken() {
ObscuredSharedPreferences sharedPref = ObscuredSharedPreferences.getPrefs(getContext(), "GlobalData", Context.MODE_PRIVATE);
boolean hasLogged = sharedPref.getBoolean("HAS_LOGGED", false);
if (!hasLogged || !GlobalData.getSharedGlobalData().isRequiresAccessToken()) return;
UserSession.setInvalidToken(true);
if (getActivity() != null) {
isErrorFromServer = true;
Utility.stopAllServices(getActivity());
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
try {
if (getActivity() != null) {
DialogManager.showForceExitAlert(getActivity(),
mContext.getString(R.string.failed_refresh_token));
}
} catch (Exception e) {
FireCrash.log(e);
// empty
}
}
});
}
}
//Interface to encryption outside of this class
/**
* Interface for HttpConnection class to communicate with encryption engine
*
* @author glen.iglesias
*/
public interface ConnectionCryptor {
String encrpyt(String data);
String decrypt(String data);
}
}

View file

@ -0,0 +1,684 @@
package com.adins.mss.base.todolist.form;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.adins.mss.base.Backup;
import com.adins.mss.base.GlobalData;
import com.adins.mss.base.R;
import com.adins.mss.base.crashlytics.FireCrash;
import com.adins.mss.base.dynamicform.CustomerFragment;
import com.adins.mss.base.dynamicform.SurveyHeaderBean;
import com.adins.mss.base.mainmenu.MainMenuActivity;
import com.adins.mss.base.timeline.TimelineManager;
import com.adins.mss.base.todolist.ToDoList;
import com.adins.mss.base.util.GsonHelper;
import com.adins.mss.base.util.Utility;
import com.adins.mss.constant.Global;
import com.adins.mss.dao.Scheme;
import com.adins.mss.dao.TaskH;
import com.adins.mss.dao.User;
import com.adins.mss.foundation.db.dataaccess.GeneralParameterDataAccess;
import com.adins.mss.foundation.db.dataaccess.SchemeDataAccess;
import com.adins.mss.foundation.db.dataaccess.TaskHDataAccess;
import com.adins.mss.foundation.db.dataaccess.TimelineDataAccess;
import com.adins.mss.foundation.db.dataaccess.TimelineTypeDataAccess;
import com.adins.mss.foundation.formatter.Tool;
import com.adins.mss.foundation.http.HttpConnectionResult;
import com.adins.mss.foundation.http.HttpCryptedConnection;
import com.adins.mss.foundation.http.MssRequestType;
import com.google.firebase.perf.FirebasePerformance;
import com.google.firebase.perf.metrics.HttpMetric;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class PrioritySectionFragment extends Fragment implements
OnItemClickListener,
Filterable {
/**
* The fragment argument representing the section number for this fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
/* STATUS */
public static final String STATUS_SEND_INIT = "New";
public static final String STATUS_SEND_DOWNLOAD = "Download";
/* PRIORITY */
public static final String PRIORITY_HIGH = "HIGH";
public static final String PRIORITY_REMINDER = "REMINDER";
public static final String PRIORITY_MEDIUM = "MEDIUM";
public static final String PRIORITY_NORMAL = "NORMAL";
public static final String PRIORITY_LOW = "LOW";
private List<TaskH> listTaskH;
private static ArrayAdapter<TaskH> priorityListAdapter;
public ToDoList toDoList;
public int searchType;
public String searchContent;
protected Spinner spinnerSearch;
LayoutInflater inflater;
private GridView gridView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView priorityCounter;
private RefreshBackgroundTask backgroundTask;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridView = (GridView) view.findViewById(R.id.gridPriority);
priorityListAdapter = new ImageAdapter(getActivity()
.getApplicationContext(), listTaskH);
priorityCounter = (TextView) view.findViewById(R.id.priorityCounter);
spinnerSearch = (Spinner) view.findViewById(R.id.priorityViewBy);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity(), R.array.cbPriorityBy, R.layout.spinner_style);
spinnerSearch.setAdapter(adapter);
spinnerSearch
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
long itemSearchBy = spinnerSearch
.getItemIdAtPosition(position);
if (itemSearchBy == 0) {
// by all
cancelRefreshTask();
listTaskH = toDoList.getListTaskInPriority(
searchType, searchContent);
priorityListAdapter = new ImageAdapter(
getActivity().getApplicationContext(),
listTaskH);
priorityListAdapter.notifyDataSetChanged();
gridView.setAdapter(priorityListAdapter);
long counter = listTaskH.size();
priorityCounter.setText(getString(R.string.task_count)+ counter);
} else if (itemSearchBy == 1) {
// by High Priority
cancelRefreshTask();
listTaskH = toDoList.getListTaskInHighPriority();
priorityListAdapter = new ImageAdapter(
getActivity().getApplicationContext(),
listTaskH);
priorityListAdapter.notifyDataSetChanged();
gridView.setAdapter(priorityListAdapter);
long counter = listTaskH.size();
priorityCounter.setText(getString(R.string.task_count)+counter);
} else if (itemSearchBy == 2) {
// by Normal Priority
cancelRefreshTask();
listTaskH = toDoList.getListTaskInNormalPriority();
priorityListAdapter = new ImageAdapter(
getActivity().getApplicationContext(),
listTaskH);
priorityListAdapter.notifyDataSetChanged();
gridView.setAdapter(priorityListAdapter);
long counter = listTaskH.size();
priorityCounter.setText(getString(R.string.task_count)+counter);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
//EMPTY
}
});
gridView.setAdapter(priorityListAdapter);
gridView.setOnItemClickListener(this);
}
@SuppressLint("ResourceAsColor")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
toDoList = new ToDoList(getActivity().getApplicationContext());
listTaskH = toDoList.getListTaskInPriority(searchType, searchContent);
ViewMapActivity.setListTaskH(listTaskH);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.priority_layout, container,
false);
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView
.findViewById(R.id.swiperefresh);
// BEGIN_INCLUDE (change_colors)
// Set the color scheme of the SwipeRefreshLayout by providing 4 color
// resource ids
mSwipeRefreshLayout.setColorSchemeColors(R.color.tv_light, R.color.tv_normal,
R.color.tv_dark, R.color.tv_darker);
mSwipeRefreshLayout
.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
initiateRefresh();
}
});
return rootView;
}
private void initiateRefresh() {
cancelRefreshTask();
backgroundTask = new RefreshBackgroundTask();
backgroundTask.execute();
}
private void cancelRefreshTask() {
if (backgroundTask != null) {
backgroundTask.cancel(true);
}
}
@Override
public void onResume() {
super.onResume();
try {
if (toDoList == null) toDoList = new ToDoList(getActivity());
MainMenuActivity.InitializeGlobalDataIfError(getActivity().getApplicationContext());
int pos = spinnerSearch.getSelectedItemPosition();
if (pos == 0) {
// by all
listTaskH = toDoList.getListTaskInPriority(searchType,
searchContent);
} else if (pos == 1) {
// by High Priority
listTaskH = toDoList.getListTaskInHighPriority();
} else if (pos == 2) {
// by Normal Priority
listTaskH = toDoList.getListTaskInNormalPriority();
} else {
listTaskH = toDoList.getListTaskInPriority(searchType,
searchContent);
}
} catch (Exception e) {
FireCrash.log(e);
if (toDoList == null) toDoList = new ToDoList(getActivity());
listTaskH = toDoList.getListTaskInPriority(searchType,
searchContent);
}
try {
priorityListAdapter.clear();
for (TaskH taskH : listTaskH) {
priorityListAdapter.add(taskH);
}
priorityListAdapter.notifyDataSetChanged();
} catch (UnsupportedOperationException e) {
try {
priorityListAdapter = new ImageAdapter(
getActivity().getApplicationContext(),
listTaskH);
priorityListAdapter.notifyDataSetChanged();
} catch (Exception e2) {
FireCrash.log(e);
}
}
try {
try {
MainMenuActivity.setDrawerCounter();
} catch (Exception e) {
FireCrash.log(e);
}
gridView.setAdapter(priorityListAdapter);
long counter = listTaskH.size();
priorityCounter.setText(getString(R.string.task_count) + counter);
} catch (Exception e) {
FireCrash.log(e);
}
}
private String getTaskListFromServer(Context activity) {
String errMsg = "";
if (Tool.isInternetconnected(activity)) {
String result;
User user = GlobalData.getSharedGlobalData().getUser();
MssRequestType requestType = new MssRequestType();
requestType.setAudit(GlobalData.getSharedGlobalData().getAuditData());
requestType.addImeiAndroidIdToUnstructured();
String json = GsonHelper.toJson(requestType);
String url = GlobalData.getSharedGlobalData().getURL_GET_TASKLIST();
boolean encrypt = GlobalData.getSharedGlobalData().isEncrypt();
boolean decrypt = GlobalData.getSharedGlobalData().isDecrypt();
HttpCryptedConnection httpConn = new HttpCryptedConnection(activity, encrypt, decrypt);
HttpConnectionResult serverResult = null;
//Firebase Performance Trace HTTP Request
HttpMetric networkMetric =
FirebasePerformance.getInstance().newHttpMetric(url, FirebasePerformance.HttpMethod.POST);
Utility.metricStart(networkMetric, json);
try {
serverResult = httpConn.requestToServer(url, json, Global.DEFAULTCONNECTIONTIMEOUT);
Utility.metricStop(networkMetric, serverResult);
} catch (Exception e) {
FireCrash.log(e);
e.printStackTrace();
errMsg = getActivity().getString(R.string.jsonParseFailed);
return errMsg;
}
List<String> listUuidTaskH = new ArrayList<>();
if (serverResult != null) {
if (serverResult.isOK()) {
try {
result = serverResult.getResult();
JsonResponseTaskList taskList = GsonHelper.fromJson(result, JsonResponseTaskList.class);
if (taskList.getStatus().getCode() == 0) {
List<TaskH> listTaskH = taskList.getListTaskList();
if (listTaskH != null && !listTaskH.isEmpty()) {
String uuidUser = GlobalData.getSharedGlobalData().getUser().getUuid_user();
TaskHDataAccess.deleteTaskHByStatus(activity, uuidUser, TaskHDataAccess.STATUS_SEND_INIT);
for (TaskH taskH : listTaskH) {
taskH.setUser(user);
taskH.setIs_verification(Global.TRUE_STRING);
String uuid_scheme = taskH.getUuid_scheme();
listUuidTaskH.add(taskH.getUuid_task_h());
Scheme scheme = SchemeDataAccess.getOne(activity, uuid_scheme);
if (scheme != null) {
taskH.setScheme(scheme);
TaskH h = TaskHDataAccess.getOneHeader(activity, taskH.getUuid_task_h());
String uuid_timelineType = TimelineTypeDataAccess.getTimelineTypebyType(activity, Global.TIMELINE_TYPE_TASK).getUuid_timeline_type();
boolean wasInTimeline = TimelineDataAccess.getOneTimelineByTaskH(activity, user.getUuid_user(), taskH.getUuid_task_h(), uuid_timelineType) != null;
if (h != null && h.getStatus() != null) {
if (!ToDoList.isOldTask(h)) {
taskH.setStatus(TaskHDataAccess.STATUS_SEND_INIT);
TaskHDataAccess.addOrReplace(activity, taskH);
if (!wasInTimeline)
TimelineManager.insertTimeline(activity, taskH);
} else {
if (taskH.getPts_date() != null) {
h.setPts_date(taskH.getPts_date());
TaskHDataAccess.addOrReplace(activity, h);
}
}
} else {
taskH.setStatus(TaskHDataAccess.STATUS_SEND_INIT);
TaskHDataAccess.addOrReplace(activity, taskH);
if (!wasInTimeline)
TimelineManager.insertTimeline(activity, taskH);
}
}
}
List<TaskH> taskHs = TaskHDataAccess.getAllTaskByStatus(activity, GlobalData.getSharedGlobalData().getUser().getUuid_user(), TaskHDataAccess.STATUS_SEND_DOWNLOAD);
taskHs.addAll(TaskHDataAccess.getAllTaskByStatus(activity, GlobalData.getSharedGlobalData().getUser().getUuid_user(), TaskHDataAccess.STATUS_SEND_SAVEDRAFT));
List<TaskH> needRemoveFromBackup = new ArrayList<>();
for (TaskH h : taskHs) {
String uuid_task_h = h.getUuid_task_h();
boolean isSame = false;
for (String uuid_from_server : listUuidTaskH) {
if (uuid_task_h.equals(uuid_from_server)) {
isSame = true;
break;
}
}
if (!isSame) {
TaskHDataAccess.deleteWithRelation(activity, h);
if(h.getStatus().equals(TaskHDataAccess.STATUS_SEND_SAVEDRAFT)) {
needRemoveFromBackup.add(h);
}
}
}
Backup backup = new Backup(activity);
backup.removeTask(needRemoveFromBackup);
}
errMsg = "noError";
return errMsg;
} else {
errMsg = result;
return errMsg;
}
} catch (Exception e) {
FireCrash.log(e);
errMsg = getActivity().getString(R.string.jsonParseFailed);
return errMsg;
}
} else {
errMsg = serverResult.getResult();
return errMsg;
}
}
return errMsg;
} else {
return errMsg;
}
}
private void onRefreshComplete(List<TaskH> result) {
// Remove all items from the ListAdapter, and then replace them with the
// new items
try {
if (result != null && !result.isEmpty())
listTaskH = result;
priorityListAdapter.clear();
for (TaskH taskH : listTaskH) {
priorityListAdapter.add(taskH);
}
priorityListAdapter.notifyDataSetChanged();
gridView.setAdapter(priorityListAdapter);
long counter = listTaskH.size();
priorityCounter.setText(getString(R.string.task_count) + counter);
} catch (UnsupportedOperationException e) {
try {
priorityListAdapter = new ImageAdapter(
getActivity().getApplicationContext(),
listTaskH);
priorityListAdapter.notifyDataSetChanged();
} catch (Exception e2) {
FireCrash.log(e);
}
} catch (Exception e) {
FireCrash.log(e);
try {
priorityListAdapter = new ImageAdapter(
getActivity().getApplicationContext(),
listTaskH);
priorityListAdapter.notifyDataSetChanged();
} catch (Exception e2) {
FireCrash.log(e);
}
}
// Stop the refreshing indicator
if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing())
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (constraint.length() == 0) {
result.count = 0;
result.values = null;
return result;
}
listTaskH = toDoList.getListTaskInPriority(
ToDoList.SEARCH_BY_ALL, (String) constraint);
result.values = listTaskH;
result.count = listTaskH.size();
searchType = ToDoList.SEARCH_BY_ALL;
searchContent = (String) constraint;
return result;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.count != 0) {
gridView.setAdapter(new ImageAdapter(getActivity(),
(List<TaskH>) results.values));
} else {
gridView.setAdapter(new ImageAdapter(getActivity(),
new ArrayList<TaskH>()));
}
}
};
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
cancelRefreshTask();
if (position < listTaskH.size()) {
TaskH item = listTaskH.get(position);
try {
Scheme scheme = null;
scheme = item.getScheme();
if (scheme == null && item.getUuid_scheme() != null) {
scheme = SchemeDataAccess.getOne(getActivity(),
item.getUuid_scheme());
if (scheme != null)
item.setScheme(scheme);
}
if (scheme == null) {
Toast.makeText(getActivity(), getActivity().getString(R.string.task_cant_seen),
Toast.LENGTH_SHORT).show();
} else {
SurveyHeaderBean header = new SurveyHeaderBean(item);
CustomerFragment fragment = CustomerFragment.create(header);
FragmentTransaction transaction = MainMenuActivity.fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.activity_open_translate, R.anim.activity_close_scale, R.anim.activity_open_scale, R.anim.activity_close_translate);
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
} catch (Exception e) {
FireCrash.log(e);
String message = getActivity().getString(R.string.task_cant_seen2) + " " + e.getMessage();
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
}
}
@SuppressLint("NewApi")
private class RefreshBackgroundTask extends
AsyncTask<Void, Void, List<TaskH>> {
int pos = 0;
String errMessage = "";
public RefreshBackgroundTask() {
try {
pos = spinnerSearch.getSelectedItemPosition();
} catch (Exception e) {
FireCrash.log(e);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing())
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
protected List<TaskH> doInBackground(Void... params) {
// Sleep for a small amount of time to simulate a background-task
try {
errMessage = getTaskListFromServer(getActivity());
} catch (Exception e) {
FireCrash.log(e);
e.printStackTrace();
}
List<TaskH> listTaskH;
if (pos == 0) {
// by all
listTaskH = toDoList.getListTaskInPriority(searchType,
searchContent);
} else if (pos == 1) {
// by High Priority
listTaskH = toDoList.getListTaskInHighPriority();
} else if (pos == 2) {
// by Normal Priority
listTaskH = toDoList.getListTaskInNormalPriority();
} else {
listTaskH = toDoList.getListTaskInPriority(searchType,
searchContent);
}
// Return a new random list of cheeses
return listTaskH;
}
@Override
protected void onPostExecute(List<TaskH> result) {
super.onPostExecute(result);
// Tell the Fragment that the refresh has completed
if (!errMessage.isEmpty() && !errMessage.equals("noError")) {
Toast.makeText(getActivity(), errMessage, Toast.LENGTH_SHORT).show();
}
try {
MainMenuActivity.setDrawerCounter();
} catch (Exception e) {
FireCrash.log(e);
}
onRefreshComplete(result);
}
}
public class ImageAdapter extends ArrayAdapter<TaskH> {
private Context mContext;
private List<TaskH> listTaskH;
public ImageAdapter(Context c, List<TaskH> listTaskH) {
super(c, R.layout.priority_item_layout, listTaskH);
mContext = c;
this.listTaskH = listTaskH;
}
@Override
public int getCount() {
return listTaskH.size();
}
@Override
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
v = inflater.inflate(R.layout.priority_item_layout, null);
LinearLayout layout = (LinearLayout) v
.findViewById(R.id.bgGridPriority);
ImageView imgStatus = (ImageView) v.findViewById(R.id.imgPriority);
ImageView imgThumb = (ImageView) v
.findViewById(R.id.imgStsPriority);
ImageView imgSLE = (ImageView) v.findViewById(R.id.ImgSLE);
TextView txtpriority = (TextView) v.findViewById(R.id.txtPriority);
TextView txtId = (TextView) v.findViewById(R.id.txtTaskID);
TextView txtName = (TextView) v.findViewById(R.id.txtName);
TextView txtStatus = (TextView) v.findViewById(R.id.txtStatusTask);
TextView txtScheme = (TextView) v.findViewById(R.id.txtScheme);
TextView slaTime = (TextView) v.findViewById(R.id.txtslatime);
TaskH taskH = listTaskH.get(position);
txtId.setText(taskH.getTask_id());
txtName.setText(taskH.getCustomer_name());
txtStatus.setText(taskH.getStatus());
txtName.setSelected(true);
Scheme scheme = taskH.getScheme();
if (scheme == null) {
scheme = SchemeDataAccess.getOne(mContext,
taskH.getUuid_scheme());
}
if (scheme != null)
txtScheme.setText(scheme.getForm_id());
String priority = taskH.getPriority();
if (priority != null) {
if (PRIORITY_HIGH.equalsIgnoreCase(priority)) {
txtpriority.setText("High Priority");
layout.setBackgroundResource(R.drawable.highpriority_background);
imgStatus.setImageResource(R.drawable.icon_high);
} else if (PRIORITY_MEDIUM.equalsIgnoreCase(priority)) {
txtpriority.setText("Medium Priority");
layout.setBackgroundResource(R.drawable.mediumpriority_background);
imgStatus.setImageResource(R.drawable.icon_medium);
} else if (PRIORITY_NORMAL.equalsIgnoreCase(priority)) {
txtpriority.setText("Normal Priority");
layout.setBackgroundResource(R.drawable.mediumpriority_background);
imgStatus.setImageResource(R.drawable.icon_medium);
} else if (PRIORITY_LOW.equalsIgnoreCase(priority)) {
txtpriority.setText("Low Priority");
layout.setBackgroundResource(R.drawable.lowpriority_background);
imgStatus.setImageResource(R.drawable.icon_low);
} else if (PRIORITY_REMINDER.equalsIgnoreCase(priority)) {
txtpriority.setText("Reminder");
layout.setBackgroundResource(R.drawable.highpriority_background);
imgStatus.setImageResource(R.drawable.icon_high);
}
}
if (TaskHDataAccess.STATUS_SEND_DOWNLOAD.equals(taskH.getStatus()))
imgThumb.setImageResource(R.drawable.ic_downloaded);
else
imgThumb.setImageResource(R.drawable.ic_undownload);
int SLA_time = Integer.parseInt(GeneralParameterDataAccess.getOne(
mContext,
GlobalData.getSharedGlobalData().getUser().getUuid_user(),
Global.GS_SLA_TIME).getGs_value());
java.util.Date assignDate = taskH.getAssignment_date();
java.util.Date dSlaTime;
if (assignDate != null) {
Long assDateMs = assignDate.getTime();
java.util.Date now = Tool.getSystemDateTime();
Long nowMs = now.getTime();
Long SLAMs = SLA_time * Long.valueOf(Global.HOUR);
Long sla_late = assDateMs + SLAMs;
dSlaTime = new Date(sla_late);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String slaDate = sdf.format(dSlaTime);
slaTime.setText(slaDate);
if (nowMs > sla_late) {
imgSLE.setImageResource(R.drawable.light_red);
slaTime.setVisibility(View.GONE);
} else
imgSLE.setImageResource(R.drawable.ic_downloaded);
}
String application = GlobalData.getSharedGlobalData()
.getAuditData().getApplication();
if (Global.APPLICATION_COLLECTION.equalsIgnoreCase(application)) {
imgSLE.setVisibility(View.GONE);
slaTime.setVisibility(View.GONE);
}
return v;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB