Mehedi Hassan Piash [Sr. Software Engineer]

July 28, 2020

Corner radius in android view like map

July 28, 2020 Posted by Piash No comments

  • We can set the marginBottom of the card view in negative value.Margin should be same value as card radius. For Example,
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MianActivity">
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="-30dp"
    app:cardCornerRadius="30dp">

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

July 22, 2020

How to call activity from a library module in android studio

July 22, 2020 Posted by Piash No comments

Java



try {
    Intent myIntent = new Intent(this,Class.forName("com.mypackage.myMainActivity")); 
   startActivity(myIntent );
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

kotlin



val intent = Intent(this, Class.forName("com.mypackage.myMainActivity"))startActivity(intent) 


July 19, 2020

Api Call with architecture component [live data]

July 19, 2020 Posted by Piash No comments
- Add gradle dependency:
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.activity:activity-ktx:1.0.0"


- Resource
data class Resource<out T>(val status: Status, val data: T?, val msg: String?) {
    companion object {
        fun <T> success(data: T?): Resource<T> {
            return Resource(Status.SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T? = null): Resource<T> {
            return Resource(Status.ERROR, data, msg)
        }

        fun <T> loading(data: T? = null): Resource<T> {
            return Resource(Status.LOADING, data, null)
        }
    }
}

enum class Status {
    SUCCESS,    ERROR,    LOADING}

- ViewModel
class BasicViewModel : ViewModel() {
    fun saveCard(tokenId: String) =
        liveData(Dispatchers.IO) {            emit(Resource.loading())
            val api = ApiClient.createService(ApiService::class.java)
            val response = api.saveCard(tokenId)
            if (response.isSuccessful) {
                emit(Resource.success(response.body()))
            } else {
                emit(Resource.error(Constants.ERROR, response.errorBody()))
            }
        }
}

- Implementation in Activity of fragment

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"    private val viewModel: PayjpViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
      
        apiCall()
    }
   

    private fun apiCall(limit: String, offset: String) {
        viewModel.paymentList(limit, offset)
            .observe(this, androidx.lifecycle.Observer { resources ->                when (resources.status) {
                    Status.LOADING -> {
                        Log.d(TAG, "Loading")
                    }

                    Status.SUCCESS -> {
                        Log.d(TAG, "PaymentInformation success : ${resources.data}")
                    }

                    Status.ERROR -> {
                        Log.d(TAG, "Error :${resources.data}")
                    }
                }
            })
    }
}


July 16, 2020

Retrofit api client with BasicAuthInterceptor

July 16, 2020 Posted by Piash No comments
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)
    }

}