Last active
February 11, 2020 07:09
-
-
Save nicemak/73a3c08d7a53ddad44fbeca817ad8428 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.database.Cursor | |
import android.graphics.Bitmap | |
import android.graphics.BitmapFactory | |
import android.graphics.Matrix | |
import android.location.Location | |
import android.net.Uri | |
import android.provider.MediaStore | |
import android.text.format.DateFormat | |
import android.util.Base64 | |
import androidx.exifinterface.media.ExifInterface | |
import com.google.gson.JsonSyntaxException | |
import org.threeten.bp.DayOfWeek | |
import org.threeten.bp.temporal.WeekFields | |
import java.io.ByteArrayOutputStream | |
import java.io.FileInputStream | |
import java.io.IOException | |
import java.net.NetworkInterface | |
import java.net.SocketTimeoutException | |
import java.net.UnknownHostException | |
import java.text.SimpleDateFormat | |
import java.util.* | |
import java.util.concurrent.TimeUnit | |
import kotlin.math.ln | |
import kotlin.math.pow | |
import kotlin.math.roundToInt | |
fun secureData(message: String, encrypt: Boolean): String = if (encrypt) CryptoUtil.encrypt(message) else CryptoUtil.decrypt(message) | |
fun getDistance(current: Location, last: Location): Float = current.distanceTo(last) | |
fun returnJson(data : String, who: String) : String = "{${data.substringAfter("[{").substringBefore("}]").substringAfter("{").substringBefore("}")}}" | |
fun returnArrayJson(data : String, who: String) : String = "[{${data.substringAfter("[{").substringBefore("}]")}}]" | |
fun getFailureError(t: Throwable) : String { | |
if (t is SocketTimeoutException) return "Connection time out." | |
if (t is JsonSyntaxException) return "Oops, something is broken, please have patience while we put pieces back together." | |
if (t is UnknownHostException) return "Unable to connect server, please check your connection" | |
return "Some thing went wrong, sorry for inconvenience." | |
} | |
fun getBitmapImageFromEncodedString(encodedImage: String): Bitmap? { | |
return try { | |
val decodedString = Base64.decode(encodedImage, Base64.DEFAULT) | |
BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size) | |
} | |
catch (e: Exception) | |
{ | |
null | |
} | |
} | |
fun initSP() { | |
EasySharedPreferenceConfig.initDefault( | |
EasySharedPreferenceConfig | |
.Builder() | |
.inputFileName(AppConstants.SP_FILE_NAME) | |
.inputMode(Context.MODE_PRIVATE) | |
.build() | |
) | |
} | |
fun daysOfWeekFromLocale(): Array<DayOfWeek> { | |
val firstDayOfWeek = WeekFields.of(Locale.getDefault()).firstDayOfWeek | |
var daysOfWeek = DayOfWeek.values() | |
// Order `daysOfWeek` array so that firstDayOfWeek is at index 0. | |
if (firstDayOfWeek != DayOfWeek.MONDAY) { | |
val rhs = daysOfWeek.sliceArray(firstDayOfWeek.ordinal..daysOfWeek.indices.last) | |
val lhs = daysOfWeek.sliceArray(0 until firstDayOfWeek.ordinal) | |
daysOfWeek = rhs + lhs | |
} | |
return daysOfWeek | |
} | |
fun getStringValue(key: String) : String = EasySharedPreference.getString(key, "") | |
fun getBooleanValue(key: String) : Boolean = EasySharedPreference.getBoolean(key, false) | |
fun getFloatValue(key: String) : Float = EasySharedPreference.getFloat(key, 0f) | |
fun getIntValue(key: String) : Int = EasySharedPreference.getInt(key, 0) | |
fun saveString(key: String, value: String) { EasySharedPreference.putString(key, value) } | |
fun saveBoolean(key: String, value: Boolean) { EasySharedPreference.putBoolean(key, value) } | |
fun saveInt(key: String, value: Int) { EasySharedPreference.putInt(key, value) } | |
fun saveFloat(key: String, value: Float) { EasySharedPreference.putFloat(key, value) } | |
fun getMacAddress(): String { | |
try { | |
val all = Collections.list(NetworkInterface.getNetworkInterfaces()) | |
for (nif in all) { | |
if (nif.name != "wlan0") continue | |
val macBytes = nif.hardwareAddress ?: return "" | |
val res1 = StringBuilder() | |
for (b in macBytes) { | |
var hex = Integer.toHexString(b.toInt() and 0xFF) | |
if (hex.length == 1) | |
hex = "0$hex" | |
res1.append("$hex:") | |
} | |
if (res1.isNotEmpty()) { | |
res1.deleteCharAt(res1.length - 1) | |
} | |
return res1.toString() | |
} | |
} catch (ex: Exception) { | |
} | |
return "" | |
} | |
fun getBase64ImageString(path: Uri) : String { | |
return try | |
{ | |
println("ImageUri: $path") | |
var bm = path.path?.let { decodeFile(it) } | |
bm = path.path?.let { rotateImageIfRequired(bm, it) } | |
val bOut = ByteArrayOutputStream() | |
bm?.compress(Bitmap.CompressFormat.JPEG, 70, bOut) | |
Base64.encodeToString(bOut.toByteArray(), Base64.DEFAULT) | |
} catch (e: Exception) { | |
println("Image Exception: $e") | |
"" | |
} | |
} | |
fun getBase64ImageString(path: String) : String { | |
return try | |
{ | |
println("ImageUri: $path") | |
var bm = decodeFile(path) | |
bm = rotateImageIfRequired(bm, path) | |
val bOut = ByteArrayOutputStream() | |
bm?.compress(Bitmap.CompressFormat.JPEG, 70, bOut) | |
Base64.encodeToString(bOut.toByteArray(), Base64.DEFAULT) | |
} catch (e: Exception) { | |
println("Image Exception: $e") | |
"" | |
} | |
} | |
fun decodeFile(path: String): Bitmap? { | |
var b: Bitmap? = null | |
try { | |
// Decode image size | |
val o = BitmapFactory.Options() | |
o.inJustDecodeBounds = true | |
var fis = FileInputStream(path) | |
BitmapFactory.decodeStream(fis, null, o) | |
fis.close() | |
val IMAGE_MAX_SIZE = 1000 | |
var scale = 1 | |
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) { | |
scale = 2.0.pow( | |
(ln( | |
IMAGE_MAX_SIZE / o.outHeight.coerceAtLeast(o.outWidth).toDouble() | |
) / ln(0.5)).roundToInt().toDouble() | |
).toInt() | |
} | |
// Decode with inSampleSize | |
val o2 = BitmapFactory.Options() | |
o2.inSampleSize = scale | |
fis = FileInputStream(path) | |
b = BitmapFactory.decodeStream(fis, null, o2) | |
fis.close() | |
} catch (e: IOException) { | |
println("decodeFile $e") | |
} | |
return b | |
} | |
/** | |
* Rotate an image if required. | |
* | |
* @param img The image bitmap | |
* @param selectedImage Image URI | |
* @return The resulted Bitmap after manipulation | |
*/ | |
@Throws(IOException::class) | |
private fun rotateImageIfRequired(img: Bitmap?, selectedImage: String): Bitmap? { | |
val ei = ExifInterface(selectedImage) | |
val orientation = | |
ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) | |
return when (orientation) { | |
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(img, 90) | |
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(img, 180) | |
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(img, 270) | |
else -> img | |
} | |
} | |
private fun rotateImage(img: Bitmap?, degree: Int): Bitmap { | |
val matrix = Matrix() | |
matrix.postRotate(degree.toFloat()) | |
val rotatedImg = Bitmap.createBitmap(img!!, 0, 0, img.width, img.height, matrix, true) | |
img.recycle() | |
return rotatedImg | |
} | |
fun getResizedBitmap(bm: Bitmap?, newWidth: Int, newHeight: Int): Bitmap? { | |
try { | |
val width = bm!!.width | |
val height = bm.height | |
val scaleWidth = newWidth.toFloat() / width | |
val scaleHeight = newHeight.toFloat() / height | |
// CREATE A MATRIX FOR THE MANIPULATION | |
val matrix = Matrix() | |
// RESIZE THE BIT MAP | |
matrix.postScale(scaleWidth, scaleHeight) | |
// "RECREATE" THE NEW BITMAP | |
val resizedBitmap = Bitmap.createBitmap( | |
bm, 0, 0, width, height, matrix, false | |
) | |
bm.recycle() | |
return resizedBitmap | |
} catch (e: Exception) { | |
return bm | |
} | |
} | |
fun getDateString(time: Long?): String { | |
if (time != null) { | |
val cal = Calendar.getInstance() | |
cal.timeInMillis = time | |
val month = when (cal[Calendar.MONTH]) { | |
Calendar.JANUARY -> "January" | |
Calendar.FEBRUARY -> "February" | |
Calendar.MARCH -> "March" | |
Calendar.APRIL -> "April" | |
Calendar.MAY -> "May" | |
Calendar.JUNE -> "June" | |
Calendar.JULY -> "July" | |
Calendar.AUGUST -> "August" | |
Calendar.SEPTEMBER -> "September" | |
Calendar.OCTOBER -> "October" | |
Calendar.NOVEMBER -> "November" | |
Calendar.DECEMBER -> "December" | |
else -> "" | |
} | |
return "$month ${cal[Calendar.DAY_OF_MONTH]}, ${cal[Calendar.YEAR]}" | |
} else return "" | |
} | |
fun formatToDigitalClock(miliSeconds: Long): String { | |
val hours = TimeUnit.MILLISECONDS.toHours(miliSeconds).toInt() % 24 | |
val minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds).toInt() % 60 | |
val seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds).toInt() % 60 | |
return when { | |
hours > 0 -> String.format("%d:%02d:%02d", hours, minutes, seconds) | |
minutes > 0 -> String.format("%02d:%02d", minutes, seconds) | |
seconds > 0 -> String.format("00:%02d", seconds) | |
else -> { "00:00" } | |
} | |
} | |
fun convertMillisToFormattedTime(dateInMilliseconds: Long, dateFormat: String) | |
: String = DateFormat.format(dateFormat, dateInMilliseconds).toString() | |
fun Date.getStringDate(format: String, locale: Locale = Locale.getDefault()): String { | |
val formatter = SimpleDateFormat(format, locale) | |
return formatter.format(this) | |
} | |
fun getCurrentDate(format: String) : String = Calendar.getInstance().time.getStringDate(format, Locale.US) | |
fun getCurrentDateTime(): Date { | |
return Calendar.getInstance().time | |
} | |
fun isValidCNIC(number: String): Boolean | |
{ | |
val check = Regex("^[0-9]{5}-[0-9]{7}-[0-9]{1}$") | |
return check.matches(number) | |
} | |
fun getRealPathFromUri(context: Context, contentUri: Uri?): String? { | |
var cursor: Cursor? = null | |
return try { | |
val proj = arrayOf(MediaStore.Images.Media.DATA) | |
println(proj) | |
cursor = context.contentResolver.query(contentUri!!, proj, null, null, null) | |
val column_index: Int = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) | |
cursor.moveToFirst() | |
cursor.getString(column_index) | |
} finally { | |
cursor?.close() | |
} | |
} | |
/* | |
fun animateBackground() | |
{ | |
val animator = ValueAnimator.ofFloat(0.0f, -1.0f) | |
animator.repeatCount = ValueAnimator.INFINITE | |
animator.interpolator = LinearInterpolator() | |
animator.duration = 10000L | |
animator.addUpdateListener{ animation -> | |
val progress = animation?.animatedValue as Float | |
val width = backgroundOne.getWidth() | |
val translationX = width * progress | |
backgroundOne.setTranslationX(translationX) | |
backgroundTwo.setTranslationX(translationX + width) | |
} | |
animator.start() | |
}*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment