Alert Dialog from different class

Alert Dialog from different class
class AlertDialog(context: Context, message: String ,onPositive: () -> Unit) {

    private val dialog: AlertDialog

    init {
        dialog = AlertDialog.Builder(context)
            .setTitle(R.string.app_name)
            .setMessage(message)
            .setPositiveButton("Yes") { dialog, _ ->                dialog.dismiss()
                onPositive.invoke()
            }            .setNegativeButton("No") { dialog, _ ->                dialog.dismiss()
            }            .setCancelable(false)
            .create()
    }

    fun show() {
        dialog.show()
    }
}


TO access

AlertDialog(this, "Are you sure you want to exit?") {    finish()
}.show()

Intent with companion Object

Intent with companion Object
companion object {
    fun launchNewActivity(activity: Activity) {
        val intent = Intent(activity, LauncherActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK        ActivityCompat.startActivity(
            activity,
            intent,
            null        )
    }
}

To access this activity call from Other activity


LauncherActivity.launchNewActivity(this)

Shared preference in Different Class

Shared preference in Different Class

Shared preference

-------------------

class AppPreferences private constructor(context: Context) {

    private val preferences = context.getSharedPreferences(PreferencesName, Context.MODE_PRIVATE)

    fun clearAll() {
        preferences.edit().clear().apply()
    }

    var status: Boolean
        get() {
            return preferences.getBoolean(Status, true)
        }
        set(value) {
            preferences.edit().putBoolean(Status, value).apply()
        }

    var isLoggedIn: Boolean
        get() {
            return preferences.getBoolean(LoggedIn, false)
        }
        set(value) {
            preferences.edit().putBoolean(LoggedIn, value).apply()
        }

    var token: String?
        get() {
            return preferences.getString(Token, null)
        }
        set(value) {
            preferences.edit().putString(Token, value).apply()
        }

    var user_display_name: String?
        get() {
            return preferences.getString(UserDisplayName, null)
        }
        set(value) {
            preferences.edit().putString(UserDisplayName, value).apply()
        }

     var userFirstName: String?
        get() {
            return preferences.getString(UserNickName, null)
        }
        set(value) {
            preferences.edit().putString(UserNickName, value).apply()
        }

    companion object {
        const val PreferencesName = "App"
        const val DefaultPreferredVideoHeight = 720

        private const val Status = "status"

        private const val Token = "token"
        private const val UserDisplayName = "user_display_name"
        private const val LoggedIn = "Loggedin"
        private const val UserNickName = "user_nicename"

        fun from(context: Context?) = context?.let { AppPreferences(it) }
    }
}



To Store Data into SharedPreference

---------------------------------

AppPreferences.from(this)?.apply {
if (!tokenValue.isEmpty()){
token = tokenValue
isLoggedIn = true
SubscriptionPreferences.from(this@LoginActivity)?.isSubscribed = true
}
status = Status
                        }


To get Value From sharedpreference

-------------------------------------

AppPreferences.from(this)?.isLoggedIn

API Calling

API Calling

API Calling 


class APIClient {
companion object {
val BASE_URL = "baseURL"

val client = OkHttpClient.Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS)
.writeTimeout(100, TimeUnit.SECONDS)
.build()

val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL).client(client).build()

val api = retrofit.create(RetrofitApi::class.java)
}
}




Interface for API


interface RetrofitApi {

    @GET(BuildConfig.categories)
    fun getCategories(): Observable<ModelClass>


    @POST(BuildConfig.authurl)
    fun Login(@Query("username") username: String,@Query("password") password: String): Observable<Loginmodel>

}


ADD MODEL class from http://www.jsonschema2pojo.org/



Call API From Activity

// Calling one API and will get whole data and parse manually
private val disposables = CompositeDisposable()
fun GetRMDCategories() { APIClient.api.getCategories() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(IoScheduler()) .subscribe( { Log.e(TAG, "GetRMDCategories: ${it} \n\n") val Response = it.string() // val Response = loadJSONFromAsset() if (Response != null) { // parseJSON(Response) displayData(Response) } }, { Log.i(TAG, "Error while GetRMDCategories: ${it.message}") } ).addTo(disposables) }





in companion object

companion object {
    fun Disposable.addTo(compositeDisposable: CompositeDisposable): Disposable =
        apply { compositeDisposable.add(this) }}

Fill data inTo Adapter

private fun displayData(Response: String) {
    ProgressBar.visibility = View.GONE    CategoryListWithItems = JsonParser().parseCategoryJson(Response)
    rv_parent.adapter =
        CategoriesAdapter(CategoryListWithItems,
            onAudioButtonClicked = { position1, audio, audioplaylist, videoDetails, playlist ->                progressbar_bottom.visibility = View.VISIBLE

                showCustomDialog(position1, audio, audioplaylist, videoDetails, playlist)
            })
}



Adapter

class CategoriesAdapter(
    private val videoItems: ArrayList<RMD_CategoryListWithItems>,
    private val onAudioButtonClicked: (position: Int, audio: AudioModel, audioPlaylist: java.util.ArrayList<AudioModel>, videoDetails: RMD_CategoryItems, playlist: java.util.ArrayList<String>) -> Unit
) : RecyclerView.Adapter<RMD_CategoriesAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v =
            LayoutInflater.from(parent.context).inflate(R.layout.item_video_category, parent, false)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return videoItems.size    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        notifyDataSetChanged()
        super.onAttachedToRecyclerView(recyclerView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val category = videoItems.get(position)
        holder.recyclerView.apply {            layoutManager =
                LinearLayoutManager(holder.recyclerView.context, RecyclerView.HORIZONTAL, false)
            holder.textView.text = category.title_name            adapter = CategoryItemsAdapter(
                category.categoryItems,
                category.category_playlist,
                context,
                category.audioPlayList,
                onAudioClick = { position1, audio, audioplaylist, videoDetails,playlist->                    onAudioButtonClicked.invoke(
                        position1,
                        audio,
                        audioplaylist,videoDetails,playlist
                    )
                }            )
        }    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val recyclerView: RecyclerView = itemView.rv_child as RecyclerView
        val textView: TextView = itemView.textView
    }

}