NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

/*
*
* @copyright : ToXSL Technologies Pvt. Ltd. < www.toxsl.com >
* @author : Shiv Charan Panjeta < [email protected] >
* All Rights Reserved.
* Proprietary and confidential : All information contained herein is, and remains
* the property of ToXSL Technologies Pvt. Ltd. and its partners.
* Unauthorized copying of this file, via any medium is strictly prohibited.
*
*/

package com.zstash.ui.base

import android.Manifest
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.*
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.location.Location
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.*
import android.provider.Settings
import android.util.Base64
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.AppUpdateType.IMMEDIATE
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.firebase.messaging.FirebaseMessaging
import com.google.gson.Gson
import com.toxsl.restfulClient.api.*
import com.zstash.BuildConfig
import com.zstash.R
import com.zstash.bannerSlider.GlideImageLoadingService
import com.zstash.model.CartProductData
import com.zstash.model.ProfileData
import com.zstash.room.AppDatabase
import com.zstash.room.RoomUtils
import com.zstash.snackBar.ActionClickListener
import com.zstash.snackBar.Snackbar
import com.zstash.snackBar.SnackbarManager
import com.zstash.snackBar.SnackbarManager.Companion.show
import com.zstash.snackBar.SnackbarType
import com.zstash.ui.activity.LoginSignUpActivity
import com.zstash.ui.activity.MainActivity
import com.zstash.ui.extensions.handleErrorForServer
import com.zstash.ui.extensions.handleMessageForServer
import com.zstash.utils.*
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import ss.com.bannerslider.Slider
import java.io.File
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

open class BaseActivity : AppCompatActivity(), SyncEventListener, View.OnClickListener,
RoomUtils.roomCallbackListener {

private var appUpdateManager: AppUpdateManager? = null
var restFullClient: RestFullClient? = null
var api: API? = null
var apiInstance: Retrofit? = null
var root: File? = null
var inflater: LayoutInflater? = null
var store: PrefStore? = null
var permCallback: PermCallback? = null
private var progressDialog: Dialog? = null
private var txtMsgTV: TextView? = null
private var reqCode: Int = 0
private var networksBroadcast: NetworksBroadcast? = null
private val networkAlertDialog: AlertDialog? = null
private var networkStatus: String? = null
private var inputMethodManager: InputMethodManager? = null
private var failureDailog: android.app.AlertDialog.Builder? = null
private var failureAlertDialog: android.app.AlertDialog? = null
private var exit: Boolean = false
var roomUtils: RoomUtils? = null
var googleApiHandle: GoogleApisHandle? = null
private var alertDialog: AlertDialog? = null

val uniqueDeviceId: String
@SuppressLint("HardwareIds")
get() = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)

val isNetworkAvailable: Boolean
get() {
val connectivityManager =
getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager
.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting
}

open fun setToolbar(title: String?, showImage: Boolean, showTitle: Boolean) {
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
googleApiHandle = GoogleApisHandle.getInstance(this)
restFullClient = RestFullClient.getInstance(this)
apiInstance = restFullClient!!.getRetrofitInstance(Const.SERVER_REMOTE_URL,BuildConfig.VERSION_NAME)
api = apiInstance!!.create(API::class.java)
Slider.init(GlideImageLoadingService(this))
[email protected](
R.anim.slide_in,
R.anim.slide_out
)
inputMethodManager = this
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
store = PrefStore(this)
initializeNetworkBroadcast()
root = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
getFirebaseToken()
strictModeThread()
transitionSlideInHorizontal()
progressDialog()
setStatusBarColor(R.color.White)
failureDailog = android.app.AlertDialog.Builder(this)
val database: AppDatabase? = AppDatabase.getDatabase(this)
roomUtils = RoomUtils.getInstance()
roomUtils!!.setDatabase(database)
keyHash()

}

override fun onResume() {
super.onResume()

}

private fun cehckUpdateONResiume(){
appUpdateManager!!
.appUpdateInfo
.addOnSuccessListener { appUpdateInfo ->
if (appUpdateInfo.updateAvailability()
== UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
) {
appUpdateManager!!.startUpdateFlowForResult(
appUpdateInfo,
IMMEDIATE,
this,
Const.APPUPDATECODE
)
}

if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
showToast(getString(R.string.app_updated_successfully))
}
}

}

private fun checkAppUpdate() {
appUpdateManager = AppUpdateManagerFactory.create(this)
val appUpdateInfoTask = appUpdateManager!!.appUpdateInfo
appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
showLog("entered"+appUpdateInfo.availableVersionCode()
+"+++"+appUpdateInfo.installStatus()
+"+++"+appUpdateInfo.updateAvailability()
)

if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
&& appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
) {
appUpdateManager!!.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.IMMEDIATE,
this,
Const.APPUPDATECODE)
}
}.addOnFailureListener {
showLog(it.message.toString()+"++++"+it.localizedMessage+"++++"+it.stackTrace)
}
}

private fun updateAppDialog(){
android.app.AlertDialog.Builder(this)
.setTitle(getString(R.string.update_app))
.setMessage(getString(R.string.app_version_error))
.setCancelable(false)
.setPositiveButton(getString(R.string.update)) { d, i ->
d.dismiss()
val appPackageName =
packageName

try {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=$appPackageName")
)
)
} catch (anfe: ActivityNotFoundException) {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")
)
)
}
} .setNegativeButton(getString(R.string.skip)) { d, i ->
d.dismiss()
}.show()
}

fun setProfileData(value: ProfileData?) {
store!!.saveString(Const.PROFILE_DATA, Gson().toJson(value, ProfileData::class.java))
}

fun getProfileData(): ProfileData? {
return Gson().fromJson(store!!.getString(Const.PROFILE_DATA), ProfileData::class.java)
}

fun getAndSetCurrentLocation(onGetLocation: (location: Location) -> Unit = {}) {
if (checkPermissions(
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
2000,
object : PermCallback {
override fun permGranted(resultCode: Int) {
getAndSetCurrentLocation()
}

override fun permDenied(resultCode: Int) {
}
})
) {
try {
if (isGPSEnabled()) {

val currentLocation = googleApiHandle?.getLastKnownLocation(this)
if (currentLocation != null) {
onGetLocation(currentLocation)

}
} else { //show enable gps dialog
buildAlertMessageNoGps()
}
} catch (e: SecurityException) {
handleException(e)
}
}
}


fun getDeviceToken(): String {
return if (store!!.getString(Const.DEVICE_TOKEN, "")!!.isEmpty()) {
uniqueDeviceId
} else {
store!!.getString(Const.DEVICE_TOKEN)!!
}
}

fun getFirebaseToken() {
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w("TAG", "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}
val token = task.result
// val msg = getString(Const.DEVICE_TOKEN, token)
store!!.saveString(Const.DEVICE_TOKEN, token.toString())
Log.e("TAG", token.toString())
})
}


open fun setStatusBarColor(color: Int = R.color.Black) {
}

fun buildAlertMessageNoGps() {

if (alertDialog != null && alertDialog!!.isShowing) {
alertDialog!!.dismiss()
}

if (alertDialog == null && !isGPSEnabled() && isFinishing) {
val builder = AlertDialog.Builder(this, R.style.GPSDialogCustom)
builder.setMessage(R.string.please_check_your_gps_otherwise_location_will_not_be_fatched)
.setTitle(R.string.location_update_failed)
.setCancelable(false)
.setPositiveButton(getString(R.string.settings)) { dialog, which ->
dialog.dismiss()
dialog.cancel()
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
alertDialog = null
}
alertDialog = builder.create()
alertDialog!!.show()
}
}


fun isGPSEnabled(): Boolean {
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}

fun initFCM() {
if (checkPlayServices()) {
if (restFullClient!!.getLoginStatus() != null) {
hitCheckApi()
} else {
gotoLoginSignUpActivity()
}

}
}


fun gotoMainActivity() {

val share = Intent(this, MainActivity::class.java)
share.putExtra("is_login", true)
if (intent.data != null) {
if (intent.data.toString() == "https://zstash.co/site/app-invite") {

} else {

try {
if (!intent.data.toString()
.startsWith("zstash://zstash.co://open?link_click_id")
) {
var string = intent.data!!.toString()
.replace("zstash://zstash.co/?utm_campaign=newProduct&id=", "")
Log.e("catch_link", "link${intent.data}")
share.putExtra(
"product_id",
string.substring(0, string.indexOf("&_branch_match_id"))
)
}
} catch (e: Exception) {
handleException(e)
}

}
}
startActivity(share)
finish()
}

fun gotoLoginActivity() {
startActivity(Intent(this, LoginSignUpActivity::class.java))
finish()
}

private fun hitCheckApi() {
val param = Api3Params()
param.put(
"DeviceDetail[device_token]",
store!!.getString(Const.DEVICE_TOKEN, getFirebaseToken().toString())!!
)
param.put("DeviceDetail[device_name]", Build.MANUFACTURER + " " + Build.MODEL)
param.put("DeviceDetail[device_type]", Const.ONE)
val call = api!!.apiCheck(param.getServerHashMap())
restFullClient!!.sendRequest(call, this)
}

fun gotoLoginSignUpActivity() {
startActivity(Intent(this, LoginSignUpActivity::class.java))
finish()
}

open fun updateDrawer() {
}

private fun initializeNetworkBroadcast() {
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
networksBroadcast = NetworksBroadcast()
registerReceiver(networksBroadcast, intentFilter)
}


private fun unregisterNetworkBroadcast() {
try {
if (networksBroadcast != null) {
unregisterReceiver(networksBroadcast)
}
} catch (e: IllegalArgumentException) {
networksBroadcast = null
}

}

private fun showNoNetworkDialog(status: String?) {
networkStatus = status
if (SnackbarManager.currentSnackbar != null) {
SnackbarManager.currentSnackbar!!.dismiss()
}
SnackbarManager.create(
Snackbar.with(this)
.type(SnackbarType.SINGLE_LINE)
.text(status!!).duration(
Snackbar
.SnackbarDuration.LENGTH_INDEFINITE
)
.actionLabel(getString(R.string.retry_caps))
.actionListener(object : ActionClickListener {
override fun onActionClicked(snackbar: Snackbar) {
if (!isNetworkAvailable) {
showNoNetworkDialog(networkStatus)
} else
SnackbarManager.currentSnackbar!!.dismiss()
}
})
)!!.show()
}

fun changeDateFormat(
dateString: String?,
sourceDateFormat: String,
targetDateFormat: String
): String {
if (dateString == null || dateString.isEmpty()) {
return ""
}
val inputDateFromat = SimpleDateFormat(sourceDateFormat, Locale.getDefault())
var date = Date()
try {
date = inputDateFromat.parse(dateString)
} catch (e: ParseException) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}

val outputDateFormat = SimpleDateFormat(targetDateFormat, Locale.getDefault())
return outputDateFormat.format(date)
}

fun changeDateFormatFromDate(sourceDate: Date?, targetDateFormat: String?): String {
if (sourceDate == null || targetDateFormat == null || targetDateFormat.isEmpty()) {
return ""
}
val outputDateFormat = SimpleDateFormat(targetDateFormat, Locale.getDefault())
return outputDateFormat.format(sourceDate)
}

protected fun checkDate(checkDate: String) {
val cal = Calendar.getInstance()
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
var serverDate: Date? = null
try {
serverDate = dateFormat.parse(checkDate)
cal.time = serverDate
val currentcal = Calendar.getInstance()
if (currentcal.after(cal)) {
val builder = androidx.appcompat.app.AlertDialog.Builder(this)
builder.setMessage(getString(R.string.contact_company_info))
builder.setTitle(getString(R.string.demo_expired))
builder.setCancelable(false)
builder.setNegativeButton(getString(R.string.close)) { _, _ -> exitFromApp() }
val alert = builder.create()
alert.show()
}
} catch (e: ParseException) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}

}

private fun checkPlayServices(): Boolean {
val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(
this,
resultCode,
Const.PLAY_SERVICES_RESOLUTION_REQUEST
)
.show()
} else {
log(getString(R.string.this_device_is_not_supported))
finish()
}
return false
}
return true
}

fun checkPermissions(
perms: Array<String>,
requestCode: Int,
permCallback: PermCallback
): Boolean {
this.permCallback = permCallback
this.reqCode = requestCode
val permsArray = ArrayList<String>()
var hasPerms = true
for (perm in perms) {
if (ContextCompat.checkSelfPermission(
this,
perm
) != PackageManager.PERMISSION_GRANTED
) {
permsArray.add(perm)
hasPerms = false
}
}
if (!hasPerms) {
val permsString = arrayOfNulls<String>(permsArray.size)
for (i in permsArray.indices) {
permsString[i] = permsArray[i]
}
ActivityCompat.requestPermissions(this@BaseActivity, permsString, Const.PERMISSION_ID)
return false
} else
return true
}

override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
var permGrantedBool = false
when (requestCode) {
Const.PERMISSION_ID -> {
for (grantResult in grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
showToast(
getString(R.string.not_sufficient_permissions)
+ getString(R.string.app_name)
+ getString(R.string.permissionss)
)
permGrantedBool = false
break
} else {
permGrantedBool = true
}
}
if (permCallback != null) {
if (permGrantedBool) {
permCallback!!.permGranted(reqCode)
} else {
permCallback!!.permDenied(reqCode)
}
}
}
}
}

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == Const.APPUPDATECODE){
if (resultCode != RESULT_OK) {
Log.e("MY_APP", "Update flow failed! Result code: $resultCode")
showToastOne("Update flow failed! Result code: $resultCode")
}

}
else{
val fragments = supportFragmentManager.fragments
for (fragment in fragments) {
fragment.onActivityResult(requestCode, resultCode, data)
}
}

}

fun exitFromApp() {
finish()
finishAffinity()
}

fun hideSoftKeyboard(): Boolean {
try {
if (currentFocus != null) {
inputMethodManager!!.hideSoftInputFromWindow(this.currentFocus!!.windowToken, 0)
return true
}
} catch (e: Exception) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}

return false
}

fun isValidMail(email: String): Boolean {
return email.matches("[a-zA-Z0-9._-]+@[a-z]+\.+[a-z]+".toRegex())
}

//return weblink.matches("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]".toRegex())
fun isValidWebLink(weblink: String): Boolean {
return weblink.matches("[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]".toRegex())
}

fun isValidPassword(password: String): Boolean {
return password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[!&^%$#@()=*/.+_-])(?=\S+$).{8,}$".toRegex())
}

fun keyHash() {
try {
val info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
if (BuildConfig.DEBUG) {
Log.e(
"KeyHash:>>>>>>>>>>>>>>>",
"" + Base64.encodeToString(md.digest(), Base64.DEFAULT)
)
}
}
} catch (e: PackageManager.NameNotFoundException) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
} catch (e: NoSuchAlgorithmException) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}

}

fun log(string: String) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
Log.e("BaseActivity", string)
}
}


fun log(title: String, message: String?) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
Log.e(title, message ?: "")
}
}

private fun progressDialog() {
progressDialog = Dialog(this)
val view = View.inflate(this, R.layout.progress_dialog, null)
progressDialog!!.requestWindowFeature(Window.FEATURE_NO_TITLE)
progressDialog!!.setContentView(view)
progressDialog!!.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
txtMsgTV = view.findViewById<View>(R.id.txtMsgTV) as TextView
progressDialog!!.setCancelable(false)
}

fun startProgressDialog() {
if (progressDialog != null && !progressDialog!!.isShowing) {
try {
progressDialog!!.show()
} catch (e: Exception) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}

}
}

fun stopProgressDialog() {
if (progressDialog != null && progressDialog!!.isShowing) {
try {
progressDialog!!.dismiss()
} catch (e: Exception) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}

}
}

override fun onSyncStart() {
startProgressDialog()
}

override fun onSyncFinish() {
stopProgressDialog()
}

open fun errorSnackBar(
errorString: String,
call: Call<String>?,
callBack: Callback<String>?
): SnackbarManager? {
val buttontext: String
buttontext = if (call != null && callBack != null) {
getString(R.string.retry_cap)
} else {
getString(R.string.exit_caps)
}
val snackBar: Snackbar = Snackbar.with(this)
.type(SnackbarType.MULTI_LINE)
.text(errorString)
.duration(Snackbar.SnackbarDuration.LENGTH_INDEFINITE)
.actionLabel(buttontext)
.actionListener(object : ActionClickListener {
override fun onActionClicked(snackbar: Snackbar) {
if (call != null && callBack != null) {
onSyncStart()
call.clone().enqueue(callBack)
} else {
finish()
}
}

})
return SnackbarManager.create(snackBar)
}


override fun onSyncFailure(
errorCode: Int,
t: Throwable?,
response: Response<String>?,
call: Call<String>?,
callBack: Callback<String>?
) {
log("error_message", if (response != null) response.message() else "")
log("error_code", errorCode.toString())
if (this.isFinishing) return
if (failureAlertDialog != null && failureAlertDialog!!.isShowing) {
failureAlertDialog!!.dismiss()
}
if (errorCode == HTTPS_RESPONSE_CODE.FORBIDDEN_ERROR || errorCode == HTTPS_RESPONSE_CODE.UN_AUTHORIZATION) {
log(getString(R.string.error), getString(R.string.session_timeout_redirecting))
showToast(getString(R.string.session_timeout_redirecting))
restFullClient!!.setLoginStatus(null)
roomUtils!!.deleteAll(Const.cartOpetation.DELETE_ALL, this)
setProfileData(null)
gotoLoginSignUpActivity()
} else if (errorCode == HTTPS_RESPONSE_CODE.SERVER_ERROR) {
showToast(getString(R.string.problem_connecting_to_the_server))
} else if (t is SocketTimeoutException || t is ConnectException) {
log(getString(R.string.error), getString(R.string.request_timeout_slow_connection))
errorSnackBar(
getString(R.string.request_timeout_slow_connection),
call,
callBack
)!!.show()
} else if (t is AppInMaintenance) {
log(getString(R.string.error), getString(R.string.api_is_in_maintenance))
failureErrorDialog(t.message!!, call, callBack)!!.show()
} else if (t is AppExpiredError) {
log(getString(R.string.error), getString(R.string.api_is_expired))
} else {
log(getString(R.string.error), if (response != null) response.message() else if (t != null) t.message else "")
var message = getString(R.string.problem_connecting_to_the_server)
try {
val json = JSONObject(response?.body()?.toString()
?: response?.errorBody()?.string() ?: "{'message':'$message'}")
if (json.has("message")){
message = json.getString("message")
if (json.handleMessageForServer("password").isNotEmpty()) {
showToastOne(json.handleMessageForServer("password"))
}
else if (json.handleMessageForServer("contact_no").isNotEmpty()) {
showToastOne(json.handleMessageForServer("contact_no"))
}
else if (json.handleMessageForServer("username").isNotEmpty()) {
showToastOne(json.handleMessageForServer("username"))
}
else{
showToastOne(message)
}
} else if (json.has("error")) {
message = json.getString("error")

if (json.handleErrorForServer("password").isNotEmpty()) {
showToastOne(json.handleErrorForServer("password").replace(""",""))
}
else if (json.handleErrorForServer("confirm_password").isNotEmpty()) {
showToastOne(json.handleErrorForServer("confirm_password").replace(""",""))
}
else if (json.handleErrorForServer("contact_no").isNotEmpty()) {
showToastOne(json.handleErrorForServer("contact_no").replace(""",""))
}
else if (json.handleErrorForServer("username").isNotEmpty()) {
showToastOne(json.handleErrorForServer("username").replace(""",""))
}
else if (json.handleErrorForServer("email").isNotEmpty()) {
showToastOne(json.handleErrorForServer("email").replace(""",""))
}
else{
showToastOne(message)
}
}
} catch (e: java.lang.Exception) {
handleException(e)
}

}

}


private fun failureErrorDialog(
errorString: String,
call: Call<String>?,
callBack: Callback<String>?
): android.app.AlertDialog? {
if (call != null && callBack != null) {
failureDailog!!.setMessage(errorString).setCancelable(false)
.setNegativeButton(getString(R.string.exit_caps)) { dialog, which -> finish() }
.setPositiveButton(getString(R.string.retry_cap)) { dialog, which ->
onSyncStart()
call.clone().enqueue(callBack)
}
} else failureDailog!!.setMessage(errorString).setCancelable(false)
.setPositiveButton(getString(R.string.exit_caps)) { dialog, which -> finish() }
failureAlertDialog = failureDailog!!.create()
return failureAlertDialog
}


fun showToast(msg: String) {
SnackbarManager.create(
Snackbar.with(this).duration(Snackbar.SnackbarDuration.LENGTH_SHORT)
.type(SnackbarType.MULTI_LINE)
.text(msg)
)!!.show()
}

fun showToastOne(msg: String) {
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()

}

fun showLog(msg: String) {
if(BuildConfig.DEBUG){
Log.e("catch_exception","Error: ${msg}")
}
}

private fun strictModeThread() {
val policy = StrictMode.ThreadPolicy.Builder()
.permitAll().build()
StrictMode.setThreadPolicy(policy)
}

private fun transitionSlideInHorizontal() {
this.overridePendingTransition(
R.anim.slide_in_right,
R.anim.slide_out_left
)
}

override fun onClick(v: View) {

}

override fun onDestroy() {
super.onDestroy()
unregisterNetworkBroadcast()
}

fun backAction() {
if (exit) {
finishAffinity()
} else {
showToastOne(getString(R.string.press_one_more_time))
exit = true
Handler().postDelayed({ exit = false }, (2 * 1000).toLong())
}
}

interface PermCallback {
fun permGranted(resultCode: Int)

fun permDenied(resultCode: Int)
}

inner class NetworksBroadcast : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val status = NetworkUtil.getConnectivityStatusString(context)
if (status == null && networkAlertDialog != null) {
networkStatus = null
networkAlertDialog.dismiss()
} else if (status != null && networkStatus == null)
showNoNetworkDialog(status)
}
}

open fun handleException(e: java.lang.Exception) {
if (androidx.databinding.library.BuildConfig.DEBUG) {
e.printStackTrace()
}
}


override fun onSyncSuccess(
responseCode: Int,
responseMessage: String,
responseUrl: String,
response: String?
) {
try {
val jsonObject = JSONObject(response!!)
if (responseUrl == Const.Login.API_LOGOUT) {
if (responseCode == Const.STATUS_OK) {
setProfileData(null)
restFullClient!!.setLoginStatus(null)
startActivity(Intent(this, LoginSignUpActivity::class.java))
}
} else if (responseUrl == Const.Login.API_CHECK) {
if (responseCode == Const.STATUS_OK) {
val data = Gson().fromJson<ProfileData>(
jsonObject.getJSONObject("detail").toString(),
ProfileData::class.java
)
val accessToken = jsonObject.getJSONObject("detail").getString("access_token")
restFullClient!!.setLoginStatus(accessToken)
setProfileData(data)
restFullClient!!.setLoginStatus(data.accessToken)
gotoMainActivity()

}
}


} catch (e: java.lang.Exception) {
handleException(e)
}
}

@SuppressLint("SimpleDateFormat")
fun getPicturePath(): String? {
val timestamp = SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().time)
val picturepath = "JPEG_" + timestamp
return picturepath
}

override fun cartData(data: CartProductData?) {

}

override fun onSuccess() {

}

override fun onDataReceived(vararg objects: Any?) {
if (objects.isNotEmpty()) {
val type: Int = objects[0] as Int
val isSuccess: Boolean = objects[1] as Boolean
when (type) {
Const.cartOpetation.DELETE_ALL -> {
store?.setInt("cartSize", 0)
store?.setInt("restaurantId", 0)
}

}
}
}

fun showDialog(arrayList: ArrayList<String>, pos: Int) {
val dialogFragment = ZoomImageDialog(arrayList, pos)
dialogFragment.show(supportFragmentManager, "dialog")
}

}
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.