Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample app : Simplify Room + LiveData #999

Merged
merged 6 commits into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 56 additions & 12 deletions app/src/main/java/com/mikepenz/fastadapter/app/PagedActivity.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.mikepenz.fastadapter.app

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.AsyncDifferConfig
Expand All @@ -14,6 +18,10 @@ import com.mikepenz.fastadapter.app.paged.DemoEntity
import com.mikepenz.fastadapter.app.paged.DemoEntityViewModel
import com.mikepenz.fastadapter.paged.PagedModelAdapter
import com.mikepenz.fastadapter.select.getSelectExtension
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.materialdesigniconic.MaterialDesignIconic
import com.mikepenz.iconics.utils.actionBar
import com.mikepenz.iconics.utils.colorInt


class PagedActivity : AppCompatActivity() {
Expand All @@ -25,6 +33,8 @@ class PagedActivity : AppCompatActivity() {
//save our FastAdapter
private lateinit var mItemAdapter: PagedModelAdapter<DemoEntity, SimpleImageItem>

private lateinit var viewModel: DemoEntityViewModel

override fun onCreate(savedInstanceState: Bundle?) {
//create the activity
super.onCreate(savedInstanceState)
Expand All @@ -36,22 +46,27 @@ class PagedActivity : AppCompatActivity() {
setSupportActionBar(binding.toolbar)
supportActionBar?.setTitle(R.string.sample_paged_list)

val asyncDifferConfig = AsyncDifferConfig.Builder<DemoEntity>(object : DiffUtil.ItemCallback<DemoEntity>() {
override fun areItemsTheSame(oldItem: DemoEntity, newItem: DemoEntity): Boolean {
return oldItem.identifier == newItem.identifier
}
val asyncDifferConfig =
AsyncDifferConfig.Builder(object : DiffUtil.ItemCallback<DemoEntity>() {
override fun areItemsTheSame(oldItem: DemoEntity, newItem: DemoEntity): Boolean {
return oldItem.identifier == newItem.identifier
}

override fun areContentsTheSame(oldItem: DemoEntity, newItem: DemoEntity): Boolean {
return oldItem == newItem
}
}).build()
override fun areContentsTheSame(oldItem: DemoEntity, newItem: DemoEntity): Boolean {
return oldItem.data1 == newItem.data1
}
}).build()

//create our ItemAdapter which will host our items
mItemAdapter = PagedModelAdapter<DemoEntity, SimpleImageItem>(asyncDifferConfig, { arg: Int -> SimpleImageItem().setPlaceholder() }) {
SimpleImageItem().withName(it.data1 ?: "").withDescription(it.data2 ?: "").apply {
mItemAdapter = PagedModelAdapter<DemoEntity, SimpleImageItem>(
asyncDifferConfig,
{ SimpleImageItem().setPlaceholder() }) {
SimpleImageItem().apply {
identifier = it.identifier.toLong()
isSelectable = true
withImage("https://raw.githubusercontent.com/mikepenz/earthview-wallpapers/develop/thumb/yang_zhuo_yong_cuo,_tibet-china-63.jpg")
withName(it.data1 ?: "")
withDescription(it.data2 ?: "")
}
}

Expand All @@ -67,14 +82,17 @@ class PagedActivity : AppCompatActivity() {
binding.rv.layoutManager = LinearLayoutManager(this)
binding.rv.adapter = mFastAdapter

val viewModel = ViewModelProvider(this, DemoEntityViewModel.DemoEntityViewModelFactory(this.application))
viewModel = ViewModelProvider(
this,
DemoEntityViewModel.DemoEntityViewModelFactory(this.application)
)
.get(DemoEntityViewModel::class.java)

//listen to data changes and pass it to adapter for displaying in recycler view
viewModel.demoEntitiesList.observe(this, { t -> mItemAdapter.submitList(t!!) })

//if we do this. the first added items will be animated :D
Handler().postDelayed({
Handler(mainLooper).postDelayed({
//restore selections (this has to be done after the items were added
mFastAdapter.withSavedInstanceState(savedInstanceState)
}, 50)
Expand All @@ -92,6 +110,32 @@ class PagedActivity : AppCompatActivity() {
super.onSaveInstanceState(outState)
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.refresh, menu)
menu.findItem(R.id.item_refresh).icon =
IconicsDrawable(this, MaterialDesignIconic.Icon.gmi_refresh).apply {
colorInt = Color.BLACK; actionBar()
}
return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
//handle the click on the back arrow click
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
R.id.item_refresh -> {
viewModel.updateEntities()
Toast.makeText(this, "Refresh DB", Toast.LENGTH_SHORT).show()
true
}
else -> super.onOptionsItemSelected(item)
}
}

override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ class SimpleImageItem : BaseItem<SimpleImageItem.ViewHolder>() {
private var mImageUrl: String? = null
private var mName: String? = null
private var mDescription: String? = null
private var isPlaceholder: Boolean = false // True when used as placeholderInterceptor by PagedModelAdapter
private var isPlaceholder: Boolean =
false // True when used as placeholderInterceptor by PagedModelAdapter

/**
* defines the type defining this item. must be unique. preferably an id
Expand Down Expand Up @@ -85,10 +86,18 @@ class SimpleImageItem : BaseItem<SimpleImageItem.ViewHolder>() {
holder.imageView.setImageBitmap(null)

//set the background for the item
val color = ctx.getThemeColor(R.attr.colorPrimary, ContextCompat.getColor(ctx, R.color.colorPrimary))
val color = ctx.getThemeColor(
R.attr.colorPrimary,
ContextCompat.getColor(ctx, R.color.colorPrimary)
)

holder.view.clearAnimation()
holder.view.foreground = FastAdapterUIUtils.getSelectablePressedBackground(ctx, FastAdapterUIUtils.adjustAlpha(color, 100), 50, true)
holder.view.foreground = FastAdapterUIUtils.getSelectablePressedBackground(
ctx,
FastAdapterUIUtils.adjustAlpha(color, 100),
50,
true
)

//load glide
holder.imageView.load(mImageUrl) {
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
package com.mikepenz.fastadapter.app.paged

import androidx.paging.DataSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query


/**
* https://www.zoftino.com/pagination-in-android-using-paging-library
*/
@Dao
interface DemoEntityLocalDAO {
//to fetch data required to display in each page
@Query("SELECT * FROM DemoEntity WHERE identifier >= :id ORDER BY identifier LIMIT :size")
fun getDemoEntitiesBySize(id: Int, size: Int): List<DemoEntity>
@Query("SELECT * FROM DemoEntity")
fun getAll(): DataSource.Factory<Int, DemoEntity>

//this is used to populate db
@Insert
fun insertDemoEntities(demoEntities: List<DemoEntity>)

@Query("UPDATE DemoEntity SET data1 = -data1")
fun updateDemoEntities()
}
Original file line number Diff line number Diff line change
@@ -1,39 +1,46 @@
package com.mikepenz.fastadapter.app.paged

import android.app.Application

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers


/**
* https://www.zoftino.com/pagination-in-android-using-paging-library
*/
class DemoEntityViewModel(application: Application) : ViewModel() {
class DemoEntityViewModel(val application: Application) : ViewModel() {
//PagedList controls data loading using data source
private val dao: DemoEntityLocalDAO =
LocalRepository.getDemoEntityDB(application).demoEntityDAO()
var demoEntitiesList: LiveData<PagedList<DemoEntity>>

init {
//instantiate DemoEntitiesDataSourceFactory
val factory = DemoEntitiesDataSourceFactory(application)
val pagedListConfig = PagedList.Config.Builder()
.setPageSize(20)
.setPrefetchDistance(20)
.setEnablePlaceholders(true)
.build()

//create PagedList Config
val config = PagedList.Config.Builder()
.setEnablePlaceholders(true)
.setInitialLoadSizeHint(10)
.setPageSize(5)
.build()
demoEntitiesList = LivePagedListBuilder(dao.getAll(), pagedListConfig).build()
}

//create LiveData object using LivePagedListBuilder which takes
//data source factory and page config as params
demoEntitiesList = LivePagedListBuilder(factory, config).build()
fun updateEntities() {
Completable.fromRunnable { dao.updateDemoEntities() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}

//factory for creating view model,
// required because we need to pass Application to view model object
class DemoEntityViewModelFactory(private val mApplication: Application) : ViewModelProvider.NewInstanceFactory() {
class DemoEntityViewModelFactory(private val mApplication: Application) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(viewModel: Class<T>): T {
return DemoEntityViewModel(mApplication) as T
}
Expand Down