import com.google.gson.GsonBuilder import okhttp3.* import okhttp3.logging.HttpLoggingInterceptor import okio.IOException import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit object ApiClient { private val okHttpClient by lazy { OkHttpClient() } private val retrofit: Retrofit by lazy { val builder = Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())) val dispatcher = Dispatcher() dispatcher.maxRequests = 1 val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY val client: OkHttpClient = okHttpClient.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .addInterceptor(BasicAuthInterceptor("basic_auth_user_name", "password")) .dispatcher(dispatcher) .build() builder.client(client).build() } fun <T> createService(tClass: Class<T>?): T { return retrofit.create(tClass) } } class BasicAuthInterceptor(user: String, password: String) : Interceptor { private val credentials: String = Credentials.basic(user, password) @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request: Request = chain.request() val authenticatedRequest: Request = request.newBuilder() .header("Authorization", credentials).build() return chain.proceed(authenticatedRequest) } }
Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.
July 16, 2020
June 30, 2020
PATH command and Bash Editing
Open bash file in text editor without hassle and save simply cltr + s:
- touch ~/.bash_profile; open ~/.bash_profile
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;
}
}


