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. 178
      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. 29
      app/src/main/res/layout/activity_session.xml

@ -5,13 +5,20 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import androidx.fragment.app.Fragment 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.R
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.fragment.SessionFragment import net.pokeranalytics.android.ui.fragment.SessionFragment
import net.pokeranalytics.android.ui.viewmodel.SessionViewModel
class SessionActivity: PokerAnalyticsActivity() { 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) { enum class IntentKey(val keyName : String) {
IS_TOURNAMENT("IS_TOURNAMENT"), IS_TOURNAMENT("IS_TOURNAMENT"),
DUPLICATE("DUPLICATE"), DUPLICATE("DUPLICATE"),
@ -47,13 +54,20 @@ class SessionActivity: PokerAnalyticsActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.activity_session) setContentView(R.layout.activity_session)
initData()
initUI() initUI()
} }
override fun onBackPressed() { override fun onBackPressed() {
setResult(Activity.RESULT_OK) setResult(Activity.RESULT_OK)
super.onBackPressed() 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() { private fun initUI() {
var sessionId: String? = null val fragmentTransaction = supportFragmentManager.beginTransaction()
if (intent.hasExtra(IntentKey.SESSION_ID.keyName)) { val fragment = SessionFragment()
sessionId = intent.getStringExtra(IntentKey.SESSION_ID.keyName) 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 android.widget.Toast
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.interpolator.view.animation.FastOutSlowInInterpolator import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DiffUtil
import com.crashlytics.android.Crashlytics import com.crashlytics.android.Crashlytics
import kotlinx.android.synthetic.main.fragment_session.* 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.RowRepresentableDiffCallback
import net.pokeranalytics.android.ui.view.SmoothScrollLinearLayoutManager import net.pokeranalytics.android.ui.view.SmoothScrollLinearLayoutManager
import net.pokeranalytics.android.ui.view.rowrepresentable.SessionRow 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.findById
import net.pokeranalytics.android.util.extensions.getNextMinuteInMilliseconds import net.pokeranalytics.android.util.extensions.getNextMinuteInMilliseconds
import java.util.* import java.util.*
@ -37,9 +39,10 @@ import java.util.*
class SessionFragment : RealmFragment(), RowRepresentableDelegate { class SessionFragment : RealmFragment(), RowRepresentableDelegate {
private lateinit var viewModel: SessionViewModel
companion object { companion object {
const val TIMER_DELAY = 60000L const val TIMER_DELAY = 60000L
const val REQUEST_CODE_NEW_CUSTOM_FIELD = 1000 const val REQUEST_CODE_NEW_CUSTOM_FIELD = 1000
} }
@ -48,7 +51,7 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
private var sessionMenu: Menu? = null private var sessionMenu: Menu? = null
private val oldRows: ArrayList<RowRepresentable> = ArrayList() private val oldRows: ArrayList<RowRepresentable> = ArrayList()
private var sessionHasBeenCustomized = false private var sessionHasBeenUserCustomized = false
private val handler: Handler = Handler() private val handler: Handler = Handler()
private val refreshTimer: Runnable = object : Runnable { private val refreshTimer: Runnable = object : Runnable {
@ -58,51 +61,43 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
} }
} }
override fun onResume() {
super.onResume()
/** Crashlytics.log("session valid=${currentSession.isValid}, managed=${currentSession.isManaged}, loaded=${currentSession.isLoaded} ")
* 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 this.refreshTimer()
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 private fun refreshTimer() {
this.updateSessionUI(false)
} }
updateSessionUI(true)
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)
} }
sessionHasBeenCustomized = false
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) toolbar.title = if (currentSession.isTournament()) getString(R.string.tournament) else getString(R.string.cash_game)
collapsingToolbar.title = toolbar.title collapsingToolbar.title = toolbar.title
@ -110,28 +105,26 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
recyclerView.adapter = sessionAdapter recyclerView.adapter = sessionAdapter
updateSessionUI(true) updateSessionUI(true)
}
override fun onResume() {
super.onResume()
Crashlytics.log("session valid=${currentSession.isValid}, managed=${currentSession.isManaged}, loaded=${currentSession.isLoaded} ") setDisplayHomeAsUpEnabled(true)
this.refreshTimer() val viewManager = SmoothScrollLinearLayoutManager(requireContext())
recyclerView.apply {
setHasFixedSize(true)
layoutManager = viewManager
} }
private fun refreshTimer() { floatingActionButton.setOnClickListener {
this.updateSessionUI(false) 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 onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_session, container, false)
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initUI()
} }
override fun onPause() { override fun onPause() {
@ -157,6 +150,50 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
return true 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) { override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
if (fromAction) { if (fromAction) {
Toast.makeText(requireContext(), "Action for row: $row", Toast.LENGTH_SHORT).show() 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) { override fun onRowValueChanged(value: Any?, row: RowRepresentable) {
sessionHasBeenCustomized = true sessionHasBeenUserCustomized = true
try { try {
currentSession.updateValue(value, row) currentSession.updateValue(value, row)
} catch (e: PAIllegalStateException) { } 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 * Update the UI with the session data
* Should be called after the initialization of the session * 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 animationDuration = if (firstDisplay) 0L else 300L
val state = currentSession.getState() when (currentSession.getState()) {
when (state) {
SessionState.PENDING, SessionState.PLANNED -> { SessionState.PENDING, SessionState.PLANNED -> {
sessionMenu?.findItem(R.id.restart)?.isVisible = false sessionMenu?.findItem(R.id.restart)?.isVisible = false
floatingActionButton.setImageResource(R.drawable.ic_outline_play) floatingActionButton.setImageResource(R.drawable.ic_outline_play)
@ -376,7 +386,7 @@ class SessionFragment : RealmFragment(), RowRepresentableDelegate {
*/ */
override fun onBackPressed() { override fun onBackPressed() {
super.onBackPressed() super.onBackPressed()
if (!sessionHasBeenCustomized) { if (!sessionHasBeenUserCustomized) {
currentSession.delete() 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 if (this.endOfUse != null) return true
return if (BuildConfig.DEBUG) { return if (BuildConfig.DEBUG) {
false //true true //false //true
} else { } else {
this._isProUser this._isProUser
} }

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