Mehedi Hassan Piash [Sr. Software Engineer]

August 17, 2021

Check all properties of null of an object using reflection [kotlin]

August 17, 2021 Posted by Piash No comments
 inline fun <reified T: Any>notNullProperties(data: T, callBack :(list: List<String>)->Unit){  
   val allNullData = mutableListOf<String>()  
   for (prop in T::class.memberProperties) {  
     if ( prop.get(data) == null){  
       allNullData.add(prop.name)  
     }  
   }  
   callBack.invoke(allNullData)  
 }  

  • Use case      

  val changePassword = ChangePassword()  
         notNullProperties(changePassword){  
           if (it.isEmpty()){  
             println("not null")  
           }else{  
             println("Null : $it")  
           }  
         }  

August 15, 2021

Kotlin : How to use if-else like condition with let block for 'null' checks

August 15, 2021 Posted by Piash No comments

Source - kotlinlang.org

  • ?. performs a safe call (calls a method or accesses a property if the receiver is non-null)
  • ?: takes the right-hand value if the left-hand value is null (the elvis operator)

Change ?. with ?: will solve this issue,

Code base as following, will run either let or run block based upon the null check.

 var someValue : String? = null  
 someValue = "SOF"  
 someValue?.let {safeSomeValue->  
 //This code block will run only if someValue is not null  
 }?:run {  
 //This code block will run only when if someValue is null, like else condition  
 }  

1. You can create an extension function, like this

 fun <T> T?.whenNull(block: () -> Unit) = this ?: block()  

2. then you call it like this

 somevalue?.let { safeSomeValue ->  
   // TODO  
 }.whenNull {  
   // execute when someValue is null  
 }  

August 07, 2021

Search filter in recyclerView android

August 07, 2021 Posted by Piash , No comments

 1. Adapter for filter search data 

 class CountryAdapter : RecyclerView.Adapter<CountryAdapter.CountryViewHolder>() {  
   private val items: ArrayList<CountryNameItem> = arrayListOf()  
   var onItemClick: ((CountryNameItem) -> Unit)? = null  
   private val itemsCopies: ArrayList<CountryNameItem> = arrayListOf()  
   fun addItems(newItems: List<CountryNameItem>) {  
     items.addAll(newItems)  
     itemsCopies.addAll(newItems)  
     notifyDataSetChanged()  
   }  
   override fun onCreateViewHolder(  
     parent: ViewGroup,  
     viewType: Int  
   ): CountryAdapter.CountryViewHolder {  
     val binding =  
       AdapterCountryItemLayoutBinding.inflate(  
         LayoutInflater.from(parent.context),  
         parent,  
         false  
       )  
     return CountryViewHolder(binding)  
   }  
   inner class CountryViewHolder(val binding: AdapterCountryItemLayoutBinding) :  
     RecyclerView.ViewHolder(binding.root) {  
     fun bind(item: CountryNameItem) {  
       binding.country = item  
       itemView.setOnClickListener {  
         onItemClick?.invoke(item)  
       }  
     }  
   }  
   override fun onBindViewHolder(holder: CountryAdapter.CountryViewHolder, position: Int) {  
     val item = items[position]  
     return holder.bind(item)  
   }  
   override fun getItemCount() = items.size  
   fun filter(sequence: CharSequence?) {  
     val temp: ArrayList<CountryNameItem> = arrayListOf()  
     if (sequence.isNullOrEmpty().not()) {  
       for (s in itemsCopies) {  
         if (s.name.toLowerCase().contains(sequence!!)) {  
           temp.add(s)  
         } else {  
           for (code in s.callingCodes) {  
             if (code.contains(sequence!!)) {  
               temp.add(s)  
             }  
           }  
         }  
       }  
     } else {  
       temp.addAll(itemsCopies)  
     }  
     items.clear()  
     items.addAll(temp)  
     notifyDataSetChanged()  
     temp.clear()  
   }  
 }  

 1. Use case of adapter in the search field 

 binding.countryFilter.doOnTextChanged { text, _, _, _ ->  
         countryAdapter.filter(text.toString())  
         text?.let {  
           if (it.isNotEmpty()) cancel.show() else cancel.hide()  
         }  
       }  
 binding.cancel.setOnClickListener {  
       binding.countryFilter.text?.clear()  
     }  

Read local json file from assets in android

August 07, 2021 Posted by Piash , No comments

 1. Extension to read JSON from assets 

 // Read json file from assets  
 fun AssetManager.readAssetsFile(fileName: String): String =  
   open(fileName).bufferedReader().use { it.readText() }  

 2. Use case of reading JSON 

  requireActivity().assets.readAssetsFile("country.json").fromPrettyJson<CountryName>()  

 3.  JSON to object and object to JSON extension 

 // Transform simple object to String with Gson  
 inline fun <reified T : Any> T.toPrettyJson() : String = Gson().toJson(this, T::class.java)  
 // Transform String Json to Object  
 inline fun <reified T : Any> String.fromPrettyJson() : T = Gson().fromJson(this , T::class.java)  
 // Transform String List Json to Object  
 inline fun <reified T : Any> String.fromPrettyJsonList() : MutableList <T> = when( this.isNotEmpty()){  
   true -> Gson().fromJson(this, object : TypeToken<MutableList<T>>() {}.type)  
   false -> mutableListOf()  
 }