Skip to content

Instantly share code, notes, and snippets.

View tirgei's full-sized avatar
🤘
Carpe Diem

Vincent Kiptirgei tirgei

🤘
Carpe Diem
View GitHub Profile
class MainActivity : AppCompatActivity() {
...
/**
* Function to fetch posts
*/
private fun fetchPosts() {
apiClient.getApiService(this).fetchPosts()
.enqueue(object : Callback<PostsResponse> {
override fun onFailure(call: Call<PostsResponse>, t: Throwable) {
/**
* Interface for defining REST request functions
*/
interface ApiService {
...
@GET(Constants.POSTS_URL)
fun fetchPosts(): Call<PostsResponse>
/**
* Retrofit instance class
*/
class ApiClient {
private lateinit var apiService: ApiService
fun getApiService(context: Context): ApiService {
// Initialize ApiService if not initialized yet
if (!::apiService.isInitialized) {
/**
* Interceptor to add auth token to requests
*/
class AuthInterceptor(context: Context) : Interceptor {
private val sessionManager = SessionManager(context)
override fun intercept(chain: Interceptor.Chain): Response {
val requestBuilder = chain.request().newBuilder()
// If token has been saved, add it to the request
class MainActivity : AppCompatActivity() {
...
/**
* Function to fetch posts
*/
private fun fetchPosts() {
// Pass the token as parameter
interface ApiService {
...
@GET(Constants.POSTS_URL)
fun fetchPosts(@Header("Authorization") token: String): Call<PostsResponse>
}
data class PostsResponse (
@SerializedName("status_code")
var status: Int,
@SerializedName("message")
var message: String,
@SerializedName("posts")
var posts: List<Post>
)
data class Post (
@SerializedName("id")
var id: Int,
@SerializedName("title")
var title: String,
@SerializedName("description")
var description: String,
class LoginActivity : AppCompatActivity() {
private lateinit var sessionManager: SessionManager
private lateinit var apiClient: ApiClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
apiClient = ApiClient()
sessionManager = SessionManager(this)
/**
* Session manager to save and fetch data from SharedPreferences
*/
class SessionManager (context: Context) {
private var prefs: SharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
companion object {
const val USER_TOKEN = "user_token"
}