Use ViewModel in SessionFragment / SessionActivity

od
Laurent 6 years ago
parent 1f774a7b30
commit da52e7d535
  1. 32
      app/src/main/java/net/pokeranalytics/android/ui/activity/SessionActivity.kt
  2. 182
      app/src/main/java/net/pokeranalytics/android/ui/fragment/SessionFragment.kt
  3. 22
      app/src/main/java/net/pokeranalytics/android/ui/viewmodel/SessionViewModel.kt
  4. 2
      app/src/main/java/net/pokeranalytics/android/util/billing/AppGuard.kt
  5. 33
      app/src/main/res/layout/activity_session.xml

@ -5,13 +5,20 @@ import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_session.*
import androidx.lifecycle.ViewModelProviders
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.fragment.SessionFragment
import net.pokeranalytics.android.ui.viewmodel.SessionViewModel
class SessionActivity: PokerAnalyticsActivity() {
private lateinit var sessionFragment: SessionFragment
val viewModel: SessionViewModel by lazy {
ViewModelProviders.of(this).get(SessionViewModel::class.java)
}
enum class IntentKey(val keyName : String) {
IS_TOURNAMENT("IS_TOURNAMENT"),
DUPLICATE("DUPLICATE"),
@ -47,13 +54,20 @@ class SessionActivity: PokerAnalyticsActivity() {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_session)
initData()
initUI()
}
override fun onBackPressed() {
setResult(Activity.RESULT_OK)
super.onBackPressed()
(sessionFragment as SessionFragment).onBackPressed()
this.sessionFragment.onBackPressed()
}
private fun initData() {
this.viewModel.isTournament = intent.getBooleanExtra(IntentKey.IS_TOURNAMENT.keyName, false)
this.viewModel.duplicate = intent.getBooleanExtra(IntentKey.DUPLICATE.keyName, false)
this.viewModel.sessionId = intent.getStringExtra(IntentKey.SESSION_ID.keyName)
}
/**
@ -61,15 +75,13 @@ class SessionActivity: PokerAnalyticsActivity() {
*/
private fun initUI() {
var sessionId: String? = null
if (intent.hasExtra(IntentKey.SESSION_ID.keyName)) {
sessionId = intent.getStringExtra(IntentKey.SESSION_ID.keyName)
}
val fragmentTransaction = supportFragmentManager.beginTransaction()
val fragment = SessionFragment()
fragmentTransaction.add(R.id.container, fragment)
fragmentTransaction.commit()
this.sessionFragment = fragment
val isTournament = intent.getBooleanExtra(IntentKey.IS_TOURNAMENT.keyName, false)
val duplicate = intent.getBooleanExtra(IntentKey.DUPLICATE.keyName, false)
val fragment = sessionFragment as SessionFragment
fragment.setData(isTournament, sessionId, duplicate)
}
}

@ -7,6 +7,7 @@ import android.view.animation.OvershootInterpolator
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DiffUtil
import com.crashlytics.android.Crashlytics
import kotlinx.android.synthetic.main.fragment_session.*
@ -30,6 +31,7 @@ import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.RowRepresentableDiffCallback
import net.pokeranalytics.android.ui.view.SmoothScrollLinearLayoutManager
import net.pokeranalytics.android.ui.view.rowrepresentable.SessionRow
import net.pokeranalytics.android.ui.viewmodel.SessionViewModel
import net.pokeranalytics.android.util.extensions.findById
import net.pokeranalytics.android.util.extensions.getNextMinuteInMilliseconds
import java.util.*
@ -37,9 +39,10 @@ import java.util.*
class SessionFragment : RealmFragment(), RowRepresentableDelegate {
private lateinit var viewModel: SessionViewModel
companion object {
const val TIMER_DELAY = 60000L
const val REQUEST_CODE_NEW_CUSTOM_FIELD = 1000
}
@ -48,7 +51,7 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
private var sessionMenu: Menu? = null
private val oldRows: ArrayList<RowRepresentable> = ArrayList()
private var sessionHasBeenCustomized = false
private var sessionHasBeenUserCustomized = false
private val handler: Handler = Handler()
private val refreshTimer: Runnable = object : Runnable {
@ -58,60 +61,6 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
}
}
/**
* Set fragment data
*/
fun setData(isTournament: Boolean, sessionId: String? = null, duplicate: Boolean) {
val realm = getRealm()
if (sessionId != null) {
val sessionRealm = realm.findById<Session>(sessionId)
if (sessionRealm != null) {
if (duplicate) { // duplicate session
realm.executeTransaction {
val session = sessionRealm.duplicate()
currentSession = session
}
sessionHasBeenCustomized = false
} else { // show existing session
currentSession = sessionRealm
sessionHasBeenCustomized = true
}
} else {
throw PAIllegalStateException("Session cannot be null here, session id = $sessionId")
}
} else { // create new session
realm.executeTransaction { executeRealm ->
currentSession = Session.newInstance(executeRealm, isTournament)
FavoriteSessionFinder.copyParametersFromFavoriteSession(currentSession, null, requireContext())
}
// Find the nearest location around the user
parentActivity?.findNearestLocation {
it?.let { location ->
realm.executeTransaction { executeRealm ->
val realmLocation = executeRealm.findById<Location>(location.id)
FavoriteSessionFinder.copyParametersFromFavoriteSession(currentSession, realmLocation, requireContext())
currentSession.location = realmLocation
}
updateSessionUI(true)
}
}
sessionHasBeenCustomized = false
}
toolbar.title = if (currentSession.isTournament()) getString(R.string.tournament) else getString(R.string.cash_game)
collapsingToolbar.title = toolbar.title
sessionAdapter = RowRepresentableAdapter(currentSession, this)
recyclerView.adapter = sessionAdapter
updateSessionUI(true)
}
override fun onResume() {
super.onResume()
@ -124,6 +73,15 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
this.updateSessionUI(false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.viewModel = activity?.run {
ViewModelProviders.of(this).get(SessionViewModel::class.java)
} ?: throw Exception("Invalid Activity")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_session, container, false)
@ -131,9 +89,44 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadOrCreateSession()
initUI()
}
/**
* Init UI
*/
private fun initUI() {
toolbar.title = if (currentSession.isTournament()) getString(R.string.tournament) else getString(R.string.cash_game)
collapsingToolbar.title = toolbar.title
sessionAdapter = RowRepresentableAdapter(currentSession, this)
recyclerView.adapter = sessionAdapter
updateSessionUI(true)
setDisplayHomeAsUpEnabled(true)
val viewManager = SmoothScrollLinearLayoutManager(requireContext())
recyclerView.apply {
setHasFixedSize(true)
layoutManager = viewManager
}
floatingActionButton.setOnClickListener {
if (this.currentSession.isValidForSave()) {
sessionHasBeenUserCustomized = true
manageSessionState()
} else {
val builder = AlertDialog.Builder(requireContext())
.setMessage(this.currentSession.getFailedSaveMessage(SaveValidityStatus.DATA_INVALID))
.setNegativeButton(R.string.ok, null)
builder.show()
}
}
}
override fun onPause() {
super.onPause()
handler.removeCallbacksAndMessages(null)
@ -157,6 +150,50 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
return true
}
private fun loadOrCreateSession() {
val realm = getRealm()
val sessionId = this.viewModel.sessionId
if (sessionId != null) {
val sessionRealm = realm.findById<Session>(sessionId)
if (sessionRealm != null) {
if (this.viewModel.duplicate) { // duplicate session
realm.executeTransaction {
val session = sessionRealm.duplicate()
currentSession = session
}
sessionHasBeenUserCustomized = false
} else { // show existing session
currentSession = sessionRealm
sessionHasBeenUserCustomized = true
}
} else {
throw PAIllegalStateException("Session cannot be null here, session id = $sessionId")
}
} else { // create new session
realm.executeTransaction { executeRealm ->
currentSession = Session.newInstance(executeRealm, this.viewModel.isTournament)
FavoriteSessionFinder.copyParametersFromFavoriteSession(currentSession, null, requireContext())
}
// Find the nearest location around the user
parentActivity?.findNearestLocation {
it?.let { location ->
realm.executeTransaction { executeRealm ->
val realmLocation = executeRealm.findById<Location>(location.id)
FavoriteSessionFinder.copyParametersFromFavoriteSession(currentSession, realmLocation, requireContext())
currentSession.location = realmLocation
}
updateSessionUI(true)
}
}
sessionHasBeenUserCustomized = false
}
}
override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
if (fromAction) {
Toast.makeText(requireContext(), "Action for row: $row", Toast.LENGTH_SHORT).show()
@ -189,7 +226,7 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
}
override fun onRowValueChanged(value: Any?, row: RowRepresentable) {
sessionHasBeenCustomized = true
sessionHasBeenUserCustomized = true
try {
currentSession.updateValue(value, row)
} catch (e: PAIllegalStateException) {
@ -203,32 +240,6 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
}
}
/**
* Init UI
*/
private fun initUI() {
setDisplayHomeAsUpEnabled(true)
val viewManager = SmoothScrollLinearLayoutManager(requireContext())
recyclerView.apply {
setHasFixedSize(true)
layoutManager = viewManager
}
floatingActionButton.setOnClickListener {
if (this.currentSession.isValidForSave()) {
sessionHasBeenCustomized = true
manageSessionState()
} else {
val builder = AlertDialog.Builder(requireContext())
.setMessage(this.currentSession.getFailedSaveMessage(SaveValidityStatus.DATA_INVALID))
.setNegativeButton(R.string.ok, null)
builder.show()
}
}
}
/**
* Update the UI with the session data
* Should be called after the initialization of the session
@ -241,8 +252,7 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
val animationDuration = if (firstDisplay) 0L else 300L
val state = currentSession.getState()
when (state) {
when (currentSession.getState()) {
SessionState.PENDING, SessionState.PLANNED -> {
sessionMenu?.findItem(R.id.restart)?.isVisible = false
floatingActionButton.setImageResource(R.drawable.ic_outline_play)
@ -376,7 +386,7 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
*/
override fun onBackPressed() {
super.onBackPressed()
if (!sessionHasBeenCustomized) {
if (!sessionHasBeenUserCustomized) {
currentSession.delete()
}
}

@ -0,0 +1,22 @@
package net.pokeranalytics.android.ui.viewmodel
import androidx.lifecycle.ViewModel
class SessionViewModel : ViewModel() {
/***
* Indicates whether the session is a tournament, or a cash game
*/
var isTournament: Boolean = false
/***
* The id of the session
*/
var sessionId: String? = null
/***
* Indicates whether a session is duplicated
*/
var duplicate: Boolean = false
}

@ -64,7 +64,7 @@ object AppGuard : PurchasesUpdatedListener {
if (this.endOfUse != null) return true
return if (BuildConfig.DEBUG) {
false //true
true //false //true
} else {
this._isProUser
}

@ -1,15 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<fragment
android:id="@+id/sessionFragment"
android:name="net.pokeranalytics.android.ui.fragment.SessionFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment_session" />
</LinearLayout>
android:layout_height="match_parent">
</FrameLayout>
<!--<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="match_parent"-->
<!-- xmlns:tools="http://schemas.android.com/tools"-->
<!-- android:orientation="vertical">-->
<!-- <fragment-->
<!-- android:id="@+id/sessionFragment"-->
<!-- android:name="net.pokeranalytics.android.ui.fragment.SessionFragment"-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="match_parent"-->
<!-- tools:layout="@layout/fragment_session" />-->
<!--</LinearLayout>-->
Loading…
Cancel
Save