OKHTTP, Show next activity after fetching the login details from API

Dear Friends,

Iam new here, iam creating an elearning app with kotlin native android, iam using OKHTTP and connecitng my API and login and then fetching the course details. its working fine. But once i click login button, it goes to next activity, i want to go to next activity once i got all the course details. Pls help me.

Find below my codes:

LoginActivity.kt

package com.example.a139_sample1

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothClass
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.Button
import android.widget.Toast
import com.example.a139_sample1.datas.lessondata
import com.example.a139_sample1.services.Apiservice
import com.example.a139_sample1.services.AuthData
import kotlin.math.log

import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.*
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.lang.Exception
import java.util.concurrent.TimeUnit

class LoginActivity : AppCompatActivity() {
    private var httpClient = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        println("login activity.....starts.......:)")
        val loginclicked = findViewById<Button>(R.id.loginbtn)
        loginclicked.setOnClickListener{

           hellolog()

        }
    }

    fun hellolog():Unit{
        val username = username.text
        val passwd = password.text
        if(username.isNullOrEmpty()){
            println("Username Should not be empty")
            showinfo("Username Should not be empty")

        }else{
            val url = "http://123.0.0.123/Service/oauth/token"
            
            val urlpara = "grant_type=password&username=$username&password=$passwd&DeviceId=appuser1202171293352236&Online=No&appid=com.el.cab"
            Apiservice().authenticate(urlpara,url)
            val i = Intent(this,CourseActivity::class.java)
            startActivity(i)
            finish()
        }
    }

    fun showinfo(msg:String){
        println("inside showInfo")
        Toast.makeText(applicationContext,"$msg",Toast.LENGTH_SHORT).show()
    }

}

Apiservice.kt

package com.example.a139_sample1.services

import android.app.Activity
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import com.example.a139_sample1.CourseActivity
import com.example.a139_sample1.LoginActivity
import com.example.a139_sample1.datas.GlobalVariables
import com.example.a139_sample1.datas.lessondata
import com.google.gson.GsonBuilder

import okhttp3.*
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.lang.Exception
import java.util.concurrent.TimeUnit

class Apiservice {
    private var httpclient = OkHttpClient()
    fun autohMethod():String{
        println("apiservice.authMethod has called.............................")
    }

    fun authenticate(urlpara:String,url:String){
        println("inside apiservise.authenticate........:)")
        val request = Request.Builder()
            .post(urlpara.toRequestBody())
            .url(url)
            .header("Content-Type","application/json")
            .header("Content-Type","application/x-ww-form-urlencoded")
            .build()
        httpclient.newCall(request).enqueue(object: Callback {
            override fun onResponse(call: Call, response: Response) {
                var responseBody = response?.body?.string()
                println(responseBody)
                println(response.code)
                when(response.code){
                    200 ->{
                        val jsonObject = JSONObject(responseBody)
                        println("test ${jsonObject.get("expires_in")}")
                        val gson = GsonBuilder().create()
                        val authData = gson.fromJson(responseBody,AuthData::class.java)
                        println(authData.deviceId)
                        getAllCourses(authData.deviceId,authData.access_token)
                    }
                    400 ->{
                        val jsonObject = JSONObject(responseBody)
                        println(jsonObject.get("error_description"))
                    }
                }

            }

            override fun onFailure(call: Call, e: IOException) {
                println("Failed to execute $e")
            }
        })
    }


    fun getAllCourses(deviceId:String,accessToken:String){
        println("Hello inside getAllCourse activity........................................")
        val url = "http://123.0.0.123/Service/api/lms/getenrolledCourseDetails/0"
        try{
            httpclient .newBuilder()
                .connectTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .build()

            val request = Request.Builder()
                .url(url)
                .header("Content-Type","applicaiton/x-www-form-urlencoded")
                .header("DeviceId",deviceId as String)
                .header("Authorization","Bearer $accessToken")
                .build()


            httpclient.newCall(request).enqueue(object:Callback{

                override fun onResponse(call: Call, response: Response) {
                    var responseBody = response.body?.string()
                    if(responseBody.isNullOrEmpty()){
                        responseBody = "No data found"
                    }
                    println(responseBody)
                    println(response.code)

                    when(response.code){
                        200->{
                            val jsonObject = JSONObject(responseBody)

                            val gson = GsonBuilder().create()
                            val courseData = gson.fromJson(responseBody,CourseData::class.java)

                            println(courseData.courseDetails.courses.elementAt(0).modules.get(0).lessions.get(0).FileFullPathUrl)
                            val len1 = courseData.courseDetails.courses.elementAt(0).modules.get(0).lessions.indices
                            for (i in len1){
                                println(courseData.courseDetails.courses.elementAt(0).modules.get(0).lessions.get(i).FileFullPathUrl)
                                GlobalVariables.lessonLinks = "$courseData.courseDetails.courses.elementAt(0).modules.get(0).lessions.get(i).FileFullPathUrl"

                            }
                            println("Length is : $len1")
                        }
                        400->{
                            val jsonObject = JSONObject(responseBody)
                            println(jsonObject.get("error_description"))
                        }
                    }

                }

                override fun onFailure(call: Call, e: IOException) {
                    println("Failed to execute $e")
                }
            })
        }catch (e: Exception){
            println("catch error $e")
        }
    }
}

  1. iam getting output, but it goes to next activity immediatelky after click on login button, i want to move the control to course screen after login authenticated and fetch all the course details and then it has to move next screen(course screen).

  2. i want to call the function (fun showinfo(msg:String)) available in in LoginActivity.kt from other classes or activities. pls help me to achieve this.

  3. i want to fetch details from api and store it in the local data classs. i can store it. but i dont know how to show and use that data’s in other activity screens. pls help me iam in urgent need…

Thanks in Advance,
Syed Abdul Rahim