Advertisement

Responsive Advertisement

Some Useful Custom utilities in kotlin

const val device_token = "device_token"

const val session_id = "session_id"

const val user_id = "user_id"
val application = MyApplication.getMyApplication()
val DEVICE_NAME = Build.DEVICE + " " + Build.MODEL + " " + Build.MANUFACTURER
val DEVICE_ID = getDeviceId()
const val user_data = "user_data"
const val currency = ""
const val latitude = "latitude"
const val longitude = "longitude"
val gson = Gson()
const val OFFERS = "OFFERS"
const val MESSAGE = "MESSAGE"
const val HISTORY = "HISTORY"
const val SERVICES = "SERVICES"
const val STATUS_COLOR1 = "#EFEFEF"
const val STATUS_COLOR2 = "#25233C"
const val STATUS_WHITE = "#FFFFFFFF"

@SuppressLint("HardwareIds")
fun getDeviceId(): String {
return Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID)
}

fun View.setMargins(
left: Int = this.marginLeft,
top: Int = this.marginTop,
right: Int = this.marginRight,
bottom: Int = this.marginBottom,
) {
layoutParams = (layoutParams as ViewGroup.MarginLayoutParams).apply {
setMargins(left, top, right, bottom)
}
}

@SuppressLint("DiscouragedApi")
fun ImageView.setImageApp(icon: String) {
val res = resources.getIdentifier(icon, "drawable", this.context.packageName)
this.setImageResource(res)
}

fun setEditText(editText: EditText) {
editText.addTextChangedListener {
if (it.isNullOrEmpty()) {
editText.setTextSize(
TypedValue.COMPLEX_UNIT_PX, editText.resources.getDimension(R.dimen._13sp)
)
editText.setBackgroundResource(R.drawable.edt_normal)
} else {
editText.setTextSize(
TypedValue.COMPLEX_UNIT_PX, editText.resources.getDimension(R.dimen._13sp)
)
editText.setBackgroundResource(R.drawable.edt_selected)
}
}
}


fun stringToBase64(str: String): String {
val encodeStr = Base64.encodeToString(str.toByteArray(charset("UTF-8")), Base64.DEFAULT)
return encodeStr
}

fun decodeBase64(str: String): String {
val decodeStr = Base64.decode(str, Base64.DEFAULT).toString(charset("UTF-8"))
return decodeStr
}

fun TextView.setTextSize2(@DimenRes size: Int) {
setTextSize(
TypedValue.COMPLEX_UNIT_PX, resources.getDimension(size)
)
}

fun EditText.setError2() {
setBackgroundResource(R.drawable.edt_error)
requestFocus()
}

fun TextView.setTextColor2(color: Int) {
setTextColor(resources.getColor(color))
}

fun TextView.setTextColor2(color: String) {
setTextColor(Color.parseColor(color))
}

fun showHidePassword(passwordView: ImageView, editText: EditText) {
var showing = true
passwordView.setOnClickListener {
if (showing) {
showing = false
editText.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
passwordView.setImageResource(R.drawable.password_hide)

} else {
showing = true
editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
passwordView.setImageResource(R.drawable.password_view)
}
if (editText.length() > 0) editText.setSelection(editText.length())
editText.typeface = ResourcesCompat.getFont(editText.context, R.font.medium)
}
}

fun TextView.setFontFamily(fontFamily: Int) {
val typeface = ResourcesCompat.getFont(context, fontFamily)
setTypeface(typeface)
}

val formatter = DecimalFormat("##,##,##0.##")
fun getPriceFormat(amount: Double): String {
formatter.format(amount)
return currency + formatter.format(amount)
}


fun TextView.textSize(dimen: Int) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(dimen))
}

fun getStringBodyFromJson(value: JsonObject): RequestBody {
return value.toString().toRequestBody("application/json".toMediaTypeOrNull())
}

fun getStringBody(value: String?): RequestBody? {
return value?.toRequestBody("text/plain".toMediaTypeOrNull())
}

fun getFIleBody(key: String, filePath: String): MultipartBody.Part {
val file = File(filePath)
return MultipartBody.Part.createFormData(
key, file.name, file.asRequestBody(("image/jpeg").toMediaTypeOrNull())
)
}

fun pdfToBase64(file: File): String {
return "data:application/pdf;base64," + fileToBase64(file)
}

fun imageToBase64(imageFile: File): String {
return "data:image/jpeg;base64," + fileToBase64(imageFile)

}

fun fileToBase64(file: File): String {
return ByteArrayOutputStream().use { outputStream ->
Base64OutputStream(outputStream, Base64.DEFAULT).use { base64 ->
file.inputStream().use { inputStream ->
inputStream.copyTo(base64)
}
}
return@use outputStream.toString()
}
}

fun showHide(it: String, editText: EditText) {
if (it.equals("Hide")) {
editText.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
} else {
editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
}
editText.setSelection(editText.length())
editText.typeface = ResourcesCompat.getFont(editText.context, R.font.normal)
}

fun setTextColor(textView: TextView, color: Int) {
textView.setTextColor(textView.context.resources.getColor(color))
}


fun getStringAssets(fileName: String): String? {
Log.d(TAG + "AssetsPath", fileName)
var jsonSting: String? = null
try {
val source = application.assets.open(fileName).source().buffer()
jsonSting = source.readByteString().string(Charset.forName("utf-8"))
} catch (e: IOException) {
e.printStackTrace()
}
return jsonSting
}

fun getString(id: Int): String {
return application.resources.getString(id)
}


fun hideSoftKeyBoard(context: Context) {
if (context is Activity) {
val view = context.currentFocus
hideSoftKeyBoard(view)
}
}

fun copyText(context: Context, string: String?) {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText("key", string)
clipboardManager.setPrimaryClip(clipData)

}

fun hideSoftKeyBoard(view: View?) {
view?.postDelayed({
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}, 100)
/* try {
val imm =
view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
} catch (e: Exception) {
e.printStackTrace()
}*/
}

fun convertDateTime(dateTime: String): String {
try {
val dateFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val date = dateFormat.parse(dateTime)
val formatter = SimpleDateFormat("dd-MMM-yyyy hh:mm aa")
val dateStr = formatter.format(date)
return dateStr
} catch (e: Exception) {
return "N/A"
}

}

fun getFullDialog(context: Context, layoutId: Int): Dialog {
val dialog = Dialog(context, android.R.style.Theme_Black_NoTitleBar_Fullscreen)

return dialog
}

fun getDialog(context: Context, layoutId: Int): Dialog {
val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.window?.setBackgroundDrawableResource(R.color.trans)
val width = Utils.getScreenWidth(context)
dialog.setContentView(layoutId)
val layout = dialog.findViewById<LinearLayout>(R.id.main_layout)
val params = layout.layoutParams
params.width = width - (width * 13 / 100)
layout.layoutParams = params
return dialog
}

fun isNetworkAvailable(context: Context): Boolean {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
if (capabilities == null) return false
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return true
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) return true
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) return true
} else {
val activeNetworkInfo = manager.activeNetworkInfo
if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
return true
}
}
return false
}

fun showToast(msg: String) {
Toast.makeText(application, msg, Toast.LENGTH_LONG).show()
}

fun showToastShort(msg: String) {
Toast.makeText(application, msg, Toast.LENGTH_SHORT).show()
}


fun loadImage(imageView: ImageView, imageUrl: String?, default: Int) {
if (imageUrl.isNullOrEmpty()) {
imageView.setImageResource(default)
} else {
Picasso.get().load(imageUrl).placeholder(default).error(default).into(imageView)
imageView.setOnLongClickListener {
ImageDialog(imageView.context, imageUrl)
true
}
}
}


fun loadImage(imageView: ImageView, imageUrl: String?) {

if (imageUrl.isNullOrEmpty()) {
imageView.setImageResource(R.drawable.loader)
} else {
Picasso.get().load(imageUrl).into(imageView)
imageView.setOnLongClickListener {
ImageDialog(imageView.context, imageUrl)
true
}
}
}

fun checkAadharNo(aadhar: String): Boolean {
val regex = "^[2-9]{1}[0-9]{3}[0-9]{4}[0-9]{4}$"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(aadhar)
return matcher.matches()
}

fun checkPANNo(panNo: String): Boolean {
val regex = "[A-Z]{5}[0-9]{4}[A-Z]{1}"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(panNo)
return matcher.matches()
}

fun checkGstinNo(gstin_no: String): Boolean {
val regex = "^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(gstin_no)
return matcher.matches()
}

fun checkBranchId(branchId: String): Boolean {
val regex = "^[A-Z]{3}[0-9]{7}$"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(branchId)
return matcher.matches()
}

fun isEmailValid(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}

fun checkMobileNo(mobile: String): Boolean {
val regex = "^[6-9]{1}[0-9]{9}$"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(mobile)
return matcher.matches()
}

fun getHtmlSpanned(htmlText: String?): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(htmlText)
}
}


fun number2digits(number: String): String {
if (number.isNullOrEmpty()) return ""
val value = String.format("%.2f", number.toDouble())
return value
}

fun number2digits(number: Double): String {
val value = String.format("%.2f", number)
return value
}

fun stringToArrayList(string: String): ArrayList<String> {
val list = ArrayList<String>()
for (item in string.trim(' ').split(",")) {
list.add(item)
}
return list
}

fun onAlertSnackbar(view: View, msg: String) {
try {
val snackbar = Snackbar.make(view, msg, Snackbar.LENGTH_SHORT)
val snackView = snackbar.view
snackView.setBackgroundColor(Color.parseColor("#1562B6"))
snackbar.show()
} catch (e: Exception) {
showToastShort(msg)
}
}

fun onSnackbar(view: View, msg: String) {
try {
val snackbar = Snackbar.make(view, msg, Snackbar.LENGTH_SHORT)
val snackView = snackbar.view
snackView.setBackgroundColor(Color.parseColor("#DD1212"))
snackbar.show()
} catch (e: Exception) {
showToastShort(msg)
}
}


fun setButtonEnabled(view: View) {
view.isClickable = false
CoroutineScope(Dispatchers.IO).launch {
delay(TimeUnit.MILLISECONDS.toMillis(1000))
withContext(Dispatchers.Main) {
view.isClickable = true
}
}
}


Post a Comment

0 Comments