Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.
April 19, 2020
April 17, 2020
Most used extension function for android
- Any[Extension]
val Boolean?.value: Boolean get() = this ?: false
val Int?.value: Int get() = this ?: 0
val Long?.value: Long get() = this ?: 0L
val Float?.value: Float get() = this ?: 0f
val Double?.value: Double get() = this ?: 0.toDouble()
val String?.value: String get() = this ?: AppConstants.Default.STRING
- Data[Extension]
inline fun <reified T : Activity> Activity.openActivity(vararg params: Pair<String, Any>) {
val intent = Intent(this, T::class.java)
intent.putExtras(*params)
startActivity(intent)
}
inline fun <reified T : Activity> Activity.openActivityFinish(vararg params: Pair<String, Any>) {
val intent = Intent(this, T::class.java)
intent.putExtras(*params)
startActivity(intent)
finish()
}
inline fun <reified T : Activity> Activity.openActivityWithClearTask(vararg params: Pair<String, Any>) {
val intent = Intent(this, T::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtras(*params)
startActivity(intent)
}
inline fun <reified T : Activity> Activity.openActivityResult(vararg params: Pair<String, Any>): Intent {
val intent = Intent(this, T::class.java)
return intent.putExtras(*params)
}
fun Activity.finishActivityResult(vararg params: Pair<String, Any>) {
val intent = Intent()
intent.putExtras(*params)
setResult(Activity.RESULT_OK, intent)
finish()
}
fun Intent.putExtras(vararg params: Pair<String, Any>): Intent {
if (params.isEmpty()) return this
params.forEach { (key, value) ->
when (value) {
is Int -> putExtra(key, value)
is Byte -> putExtra(key, value)
is Char -> putExtra(key, value)
is Long -> putExtra(key, value)
is Float -> putExtra(key, value)
is Short -> putExtra(key, value)
is Double -> putExtra(key, value)
is Boolean -> putExtra(key, value)
is Bundle -> putExtra(key, value)
is String -> putExtra(key, value)
is IntArray -> putExtra(key, value)
is ByteArray -> putExtra(key, value)
is CharArray -> putExtra(key, value)
is LongArray -> putExtra(key, value)
is FloatArray -> putExtra(key, value)
is Parcelable -> putExtra(key, value)
is ShortArray -> putExtra(key, value)
is DoubleArray -> putExtra(key, value)
is BooleanArray -> putExtra(key, value)
is CharSequence -> putExtra(key, value)
is Array<*> -> {
when {
value.isArrayOf<String>() ->
putExtra(key, value as Array<String?>)
value.isArrayOf<Parcelable>() ->
putExtra(key, value as Array<Parcelable?>)
value.isArrayOf<CharSequence>() ->
putExtra(key, value as Array<CharSequence?>)
else -> putExtra(key, value)
}
}
is Serializable -> putExtra(key, value)
}
}
return this
}
fun ResponseBody.jsonData(): JSONObject {
return JSONObject(this.string())
}
inline fun <T : Any, R> T?.ifNotNullOrElse(ifNotNullPath: (T) -> R, elsePath: () -> R) =
let { if (it == null) elsePath() else ifNotNullPath(it) }
fun AssetManager.readAssetsFile(fileName: String): String =
open(fileName).bufferedReader().use { it.readText() }
inline fun <reified T> String.getObjectFromJson(): T {
return Gson().fromJson(this, T::class.java)
}
fun Activity.countryName(): ArrayList<ItemEntity<CountryCodeItem>> {
val sortList: ArrayList<ItemEntity<CountryCodeItem>> = arrayListOf()
val countryData =
this.assets.readAssetsFile("country.json").getObjectFromJson<CountryCode>()
for (data in countryData) {
val item: ItemEntity<CountryCodeItem> = ItemEntity()
item.value = data
val letters = data.name.substring(0, 1).toUpperCase()
if (letters.matches(AppConstants.Regex.A_Z.toRegex())) {
item.setSortLetters(letters.toUpperCase())
} else {
item.setSortLetters(AppConstants.Separator.HASH)
}
sortList.add(item)
}
return sortList
}
- View[Extension]
fun View.hide() {
this.visibility = View.GONE
}
fun View.show() {
this.visibility = View.VISIBLE
}
fun Context.showToast(message: String, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
fun Int.dpToPx(): Int {
return (this * Resources.getSystem().displayMetrics.density).toInt()
}
fun Int.pixelToDp(): Int {
return (this / Resources.getSystem().displayMetrics.density).toInt()
}
fun Activity.baseActivity(): BaseActivity {
return this as BaseActivity
}
inline var TextView.underline: Boolean
set(visible) {
paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
}
get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG
fun Fragment.showFragment(fragment: DialogFragment) {
val activeFragment = childFragmentManager.findFragmentByTag(AppConstants.Dialog.DIALOG)
if (activeFragment == null) {
fragment.show(childFragmentManager.beginTransaction(), AppConstants.Dialog.DIALOG)
} else {
childFragmentManager.beginTransaction().remove(activeFragment)
}
}
fun TextInputEditText.isValidEmailPhone(): Boolean {
if (this.text.isNullOrBlank()) {
this.error = this.context.resources.getString(R.string.please_enter_your_mobile_or_email)
return false
}
return if (Patterns.PHONE.matcher(this.text.toString())
.matches() || Patterns.EMAIL_ADDRESS.matcher(this.text.toString()).matches()
) {
true
} else {
this.error = this.context.resources.getString(R.string.please_enter_your_mobile_or_email)
false
}
}
fun TextInputEditText.isValidPassword(): Boolean {
return if (this.text.isNullOrBlank()) {
this.error = this.context.resources.getString(R.string.please_enter_your_password)
false
} else {
true
}
}
fun View.enableDisableEffect() {
if (this.isEnabled) {
this.alpha = 1.0f
} else {
this.alpha = 0.5f
}
}
December 12, 2019
FlatList Pagination Two Times Call Problem in React-Native
There is a common problem while working with FlatList pagination. It calls two times with out any reason. We can solve it in different ways.But I have a very effect way which is worked for me.
Try to implement
onMomentumScrollBegin on FlatList :constructor(props) {
super(props);
this.onEndReachedCalledDuringMomentum = true;
}
<FlatList
...
onEndReached={this.onEndReached.bind(this)}
onEndReachedThreshold={0.5}
onMomentumScrollBegin={() => { this.onEndReachedCalledDuringMomentum = false; }}
/>
and modify your onEndReached
onEndReached = ({ distanceFromEnd }) => {
if(!this.onEndReachedCalledDuringMomentum){
this.fetchData();
this.onEndReachedCalledDuringMomentum = true;
}
}
November 09, 2019
React native PATH variable set up in Mac
- Enter the given line to your Mac terminal
nano ~/.bash_profile or nano ~/.zshrc
- Copy and past given line to your bash_profile file
export ANDROID_HOME=~/Library/Android/sdk/
export PATH=$PATH:~/android-sdks/platform-tools/export PATH=$PATH:~/android-sdks/tools/export PATH=$PATH:~/android-sdks/tools/adb
- cltr S
- cltr x
- Enter
- source ~/.bash_profile or source ~/.zshrc
November 02, 2019
The Rest/Spread Operator in JavaScript
One of the most interesting features added to ES2015 was the spread operator. This operator makes copying and merging arrays a lot simpler. Rather than calling the
concat() or slice() method, you could use the ... operator:const arr1 = [10, 20, 30];
// make a copy of arr1
const copy = [...arr1];
console.log(copy); // → [10, 20, 30]
const arr2 = [40, 50];
// merge arr2 with arr1
const merge = [...arr1, ...arr2];
console.log(merge); // → [10, 20, 30, 40, 50]
The spread operator also comes in handy in situations where an array must be passed in as separate arguments to a function. For example:
const arr = [10, 20, 30]
// equivalent to
// console.log(Math.max(10, 20, 30));
console.log(Math.max(...arr)); // → 30
ES2018 further expands this syntax by adding spread properties to object literals. With the spread properties you can copy own enumerable properties of an object onto a new object. Consider the following example:
const obj1 = {
a: 10,
b: 20
};
const obj2 = {
...obj1,
c: 30
};
console.log(obj2); // → {a: 10, b: 20, c: 30}
In this code, the
... operator is used to retrieve the properties of obj1 and assign them to obj2. Prior to ES2018, attempting to do so would throw an error. If there are multiple properties with the same name, the property that comes last will be used:const obj1 = {
a: 10,
b: 20
};
const obj2 = {
...obj1,
a: 30
};
console.log(obj2); // → {a: 30, b: 20}
Spread properties also provide a new way to merge two or more objects, which can be used as an alternative to the
Object.assign() method:const obj1 = {a: 10};
const obj2 = {b: 20};
const obj3 = {c: 30};
// ES2018
console.log({...obj1, ...obj2, ...obj3}); // → {a: 10, b: 20, c: 30}
// ES2015
console.log(Object.assign({}, obj1, obj2, obj3)); // → {a: 10, b: 20, c: 30}
Note, however, that spread properties do not always produce the same result as
Object.assign(). Consider the following code:Object.defineProperty(Object.prototype, 'a', {
set(value) {
console.log('set called!');
}
});
const obj = {a: 10};
console.log({...obj});
// → {a: 10}
console.log(Object.assign({}, obj));
// → set called!
// → {}
In this code, the
Object.assign() method executes the inherited setter property. Conversely, the spread properties simply ignore the setter.
It's important to remember that spread properties only copy enumerable properties. In the following example, the
type property won’t show up in the copied object because its enumerable attribute is set to false:const car = {
color: 'blue'
};
Object.defineProperty(car, 'type', {
value: 'coupe',
enumerable: false
});
console.log({...car}); // → {color: "blue"}
Inherited properties are ignored even if they are enumerable:
const car = {
color: 'blue'
};
const car2 = Object.create(car, {
type: {
value: 'coupe',
enumerable: true,
}
});
console.log(car2.color); // → blue
console.log(car2.hasOwnProperty('color')); // → false
console.log(car2.type); // → coupe
console.log(car2.hasOwnProperty('type')); // → true
console.log({...car2}); // → {type: "coupe"}
In this code,
car2 inherits the color property from car. Because spread properties only copy the own properties of an object, color is not included in the return value.
Keep in mind that spread properties can only make a shallow copy of an object. If a property holds an object, only the reference to the object will be copied:
const obj = {x: {y: 10}};
const copy1 = {...obj};
const copy2 = {...obj};
console.log(copy1.x === copy2.x); // → true
The
x property in copy1 refers to the same object in memory that x in copy2 refers to, so the strict equality operator returns true.
Another useful feature added to ES2015 was rest parameters, which enabled JavaScript programmers to use
... to represent values as an array. For example:const arr = [10, 20, 30];
const [x, ...rest] = arr;
console.log(x); // → 10
console.log(rest); // → [20, 30]
Here, the first item in
arr is assigned to x, and remaining elements are assigned to the rest variable. This pattern, called array destructuring, became so popular that the Ecma Technical Committee decided to bring similar functionality to objects:const obj = {
a: 10,
b: 20,
c: 30
};
const {a, ...rest} = obj;
console.log(a); // → 10
console.log(rest); // → {b: 20, c: 30}
This code uses the rest properties in a destructuring assignment to copy the remaining own enumerable properties into a new object. Note that rest properties must always appear at the end of the object, otherwise an error is thrown:
const obj = {
a: 10,
b: 20,
c: 30
};
const {...rest, a} = obj; // → SyntaxError: Rest element must be last element
Also keep in mind that using multiple rest syntaxes in an object causes an error unless they are nested:
const obj = {
a: 10,
b: {
x: 20,
y: 30,
z: 40
}
};
const {b: {x, ...rest1}, ...rest2} = obj; // no error
const {...rest, ...rest2} = obj; // → SyntaxError: Rest element must be last


