Hello, everybody, I've a question. I get an error ...
# android
h
Hello, everybody, I've a question. I get an error " kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized".  binding cannot initialized in getRetrofitClient().  What mistake did I make? Or there any way or other technologies to fix this issue?  If I don't use the 2nd line of getRetrofitClient(), the app works. Thanks in advance.
Copy code
lass LoginFragment : Fragment() {

    private lateinit var binding: FragmentLoginBinding
    private val viewModel: AuthViewModel by viewModels()
    /* private val viewModel:AuthViewModel by lazy{
         ViewModelProvider(this).get(AuthViewModel::class.java)
     }*/

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentLoginBinding.inflate(inflater, container, false)
     ........
      return binding.root
   }

  fun reqBody(): String {

        Log.d("LogFrag", "reqBody's binding$binding")

        val clientIdentifier = binding.edittxtClientIdentifier.text.toString().trim()

        val pass = binding.editTextTextPassword.text.toString().trim()

        viewModel.login(
            clientIdentifier,
            pass
        )

        val rootObject = JSONObject()
        rootObject.put("ClientIdentifier", clientIdentifier)
        rootObject.put("Password", pass)
        encrypt(rootObject.toString(), publicKey)

        val encrypted = encrypt(rootObject.toString(), publicKey)

        return encrypted
    }



fun <Request> getRetrofitClient(authenticator: Authenticator? = null): OkHttpClient {

    val finalEncr=reqBody()                //Error shows on this

    val body = "{\r\n    \"Data\":\"$finalEncr\"\r\n}"
        .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
Copy code
return OkHttpClient.Builder()
        .addInterceptor { chain ->
            chain.proceed(chain.request().newBuilder().also {
                it.addHeader("Accept", "application/json")
                it.method("POST", body)

            }.build())
        }.also { client ->
            authenticator?.let { client.authenticator(it) }
            if (BuildConfig.DEBUG) {
                val logging = HttpLoggingInterceptor()
                logging.setLevel(HttpLoggingInterceptor.Level.BODY)
                client.addInterceptor(logging)
            }
        }.build()
}
Copy code
class RemoteDataSource {

    @RequiresApi(Build.VERSION_CODES.O)
    fun <Api> buildApi(
        api: Class<Api>,
        context: Context
    ): Api {

        val authenticator = TokenAuthenticator(context, buildTokenApi())
        Log.d("RemoteDataSource", "buildApi")

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(LoginFragment().getRetrofitClient<Any>(authenticator))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(api)
    }
Copy code
@RequiresApi(Build.VERSION_CODES.O)
    fun buildTokenApi(): TokenRefreshApi {
        Log.d("RemoteDataSource", "buildTokenApi")

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(LoginFragment().getRetrofitClient<Any>())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(TokenRefreshApi::class.java)
    }

}
l
First of all, when pasting a lot of code, it is appreciated when it is inside a code snippet so it does not pollute the channel. Now, that error means that you are trying to access a variable (binding) before it is initialized. Maybe you have a logic error or a race condition.
j
you are using the view binding somewhere before it is assigned in the onCreateView lifecycle method.
I would suggest reviewing this page and following their guidelines about viewbinding in fragments: https://developer.android.com/topic/libraries/view-binding
z
Why are you creating a fragment just to get a retrofit client instance ?
i
@Luke He ignores the rules. Each post the same. I decide to ignore him. Hope others will do the same. Maybe he’ll stop
@Hovhannes please use threads!