Skip to content

Commit

Permalink
Fix crash in db viewer and some ui + injection tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
premnirmal committed Jun 27, 2022
1 parent e45d409 commit 44979c2
Show file tree
Hide file tree
Showing 15 changed files with 124 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.github.premnirmal.ticker.analytics.Analytics
import com.github.premnirmal.ticker.components.Injector
import com.github.premnirmal.ticker.model.IStocksProvider
import com.github.premnirmal.ticker.model.IStocksProvider.FetchState
import com.github.premnirmal.ticker.showDialog
Expand All @@ -23,10 +24,9 @@ abstract class BaseActivity<T: ViewBinding> : AppCompatActivity() {

abstract val simpleName: String
abstract val binding: T
@Inject internal lateinit var stocksProvider: IStocksProvider
@Inject internal lateinit var analytics: Analytics
open val subscribeToErrorEvents = true
private var isErrorDialogShowing = false
private val holder: InjectionHolder by lazy { InjectionHolder() }

override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase))
Expand All @@ -37,15 +37,19 @@ abstract class BaseActivity<T: ViewBinding> : AppCompatActivity() {
) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
analytics.trackScreenView(simpleName, this)
savedInstanceState?.let { isErrorDialogShowing = it.getBoolean(IS_ERROR_DIALOG_SHOWING, false) }
}

override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
holder.analytics.trackScreenView(simpleName, this)
}

override fun onResume() {
super.onResume()
if (subscribeToErrorEvents) {
lifecycleScope.launch {
stocksProvider.fetchState.collect { state ->
holder.stocksProvider.fetchState.collect { state ->
if (state is FetchState.Failure) {
if (this.isActive && !isErrorDialogShowing && !isFinishing) {
isErrorDialogShowing = true
Expand Down Expand Up @@ -83,4 +87,13 @@ abstract class BaseActivity<T: ViewBinding> : AppCompatActivity() {
companion object {
private const val IS_ERROR_DIALOG_SHOWING = "IS_ERROR_DIALOG_SHOWING"
}

class InjectionHolder {
@Inject internal lateinit var analytics: Analytics
@Inject internal lateinit var stocksProvider: IStocksProvider

init {
Injector.appComponent.inject(this)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import com.github.premnirmal.ticker.AppPreferences
import com.github.premnirmal.ticker.StocksApp
import com.github.premnirmal.ticker.UpdateReceiver
import com.github.premnirmal.ticker.analytics.GeneralProperties
import com.github.premnirmal.ticker.base.BaseActivity
import com.github.premnirmal.ticker.base.BaseFragment
import com.github.premnirmal.ticker.debug.DbViewerActivity
import com.github.premnirmal.ticker.debug.DbViewerViewModel
import com.github.premnirmal.ticker.home.HomeFragment
import com.github.premnirmal.ticker.home.HomeViewModel
Expand All @@ -20,25 +20,21 @@ import com.github.premnirmal.ticker.model.StocksProvider
import com.github.premnirmal.ticker.network.NewsProvider
import com.github.premnirmal.ticker.network.StocksApi
import com.github.premnirmal.ticker.network.UserAgentInterceptor
import com.github.premnirmal.ticker.news.GraphActivity
import com.github.premnirmal.ticker.news.GraphViewModel
import com.github.premnirmal.ticker.news.NewsFeedViewModel
import com.github.premnirmal.ticker.news.QuoteDetailActivity
import com.github.premnirmal.ticker.news.QuoteDetailViewModel
import com.github.premnirmal.ticker.notifications.DailySummaryNotificationReceiver
import com.github.premnirmal.ticker.portfolio.AddAlertsActivity
import com.github.premnirmal.ticker.portfolio.AddNotesActivity
import com.github.premnirmal.ticker.portfolio.AddPositionActivity
import com.github.premnirmal.ticker.portfolio.AddPositionViewModel
import com.github.premnirmal.ticker.portfolio.AlertsViewModel
import com.github.premnirmal.ticker.portfolio.NotesViewModel
import com.github.premnirmal.ticker.portfolio.PortfolioViewModel
import com.github.premnirmal.ticker.portfolio.StocksAdapter
import com.github.premnirmal.ticker.portfolio.search.SearchActivity
import com.github.premnirmal.ticker.portfolio.search.SearchFragment
import com.github.premnirmal.ticker.portfolio.search.SearchViewModel
import com.github.premnirmal.ticker.repo.StocksStorage
import com.github.premnirmal.ticker.settings.SettingsFragment
import com.github.premnirmal.ticker.settings.WidgetSettingsActivity
import com.github.premnirmal.ticker.settings.WidgetSettingsFragment
import com.github.premnirmal.ticker.widget.RefreshReceiver
import com.github.premnirmal.ticker.widget.RemoteStockViewAdapter
Expand All @@ -58,26 +54,16 @@ interface AppComponent {

// Activities

fun inject(mainActivity: MainActivity)

fun inject(addPositionActivity: AddPositionActivity)
fun inject(stocksApp: BaseActivity.InjectionHolder)

fun inject(addNotesActivity: AddNotesActivity)
fun inject(mainActivity: MainActivity)

fun inject(addAlertsActivity: AddAlertsActivity)

fun inject(splashActivity: SplashActivity)

fun inject(newsFeedActivity: QuoteDetailActivity)

fun inject(graphActivity: GraphActivity)

fun inject(searchActivity: SearchActivity)

fun inject(widgetSettingsActivity: WidgetSettingsActivity)

fun inject(dbViewerActivity: DbViewerActivity)

// Components

fun inject(stocksApp: StocksApp.InjectionHolder)
Expand Down Expand Up @@ -163,4 +149,6 @@ interface AppComponent {
fun inject(searchViewModel: SearchViewModel)

fun inject(viewModel: PortfolioViewModel)

fun inject(viewModel: AddPositionViewModel)
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,19 @@ import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.github.premnirmal.ticker.base.BaseActivity
import com.github.premnirmal.ticker.components.Injector
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.tickerwidget.databinding.ActivityDbViewerBinding

class DbViewerActivity : BaseActivity<ActivityDbViewerBinding>() {
override val binding: (ActivityDbViewerBinding) by viewBinding(ActivityDbViewerBinding::inflate)

override val simpleName: String
get() = "DebugViewerActivity"
override val simpleName = "DebugViewerActivity"
override val subscribeToErrorEvents = false

private val viewModel: DbViewerViewModel by viewModels()


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Injector.appComponent.inject(this)
binding.toolbar.setNavigationOnClickListener {
finish()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ class DbViewerViewModel(application: Application) : AndroidViewModel(application
<th>dividendDate</th>
<th>earningsDate</th>
<th>marketCap</th>
<th>marketState</th>
<th>isTradeable</th>
<th>isTriggerable</th>
</tr>
"""
)
Expand Down Expand Up @@ -147,7 +149,9 @@ class DbViewerViewModel(application: Application) : AndroidViewModel(application
.append("<td>${quote.dividendDate}</td>")
.append("<td>${quote.earningsDate}</td>")
.append("<td>${quote.marketCap}</td>")
.append("<td>${quote.marketState}</td>")
.append("<td>${quote.isTradeable}</td>")
.append("<td>${quote.isTriggerable}</td>")
.append("</tr>")

val holdings = it.holdings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import androidx.appcompat.app.AlertDialog.Builder
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.github.premnirmal.ticker.AppPreferences
import com.github.premnirmal.ticker.analytics.Analytics
import com.github.premnirmal.ticker.analytics.ClickEvent
import com.github.premnirmal.ticker.base.BaseActivity
import com.github.premnirmal.ticker.components.Injector
Expand Down Expand Up @@ -49,6 +50,7 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), BottomNavigationView.O
@Inject internal lateinit var appPreferences: AppPreferences
@Inject internal lateinit var widgetDataProvider: WidgetDataProvider
@Inject internal lateinit var commitsProvider: CommitsProvider
@Inject internal lateinit var analytics: Analytics

private var currentChild: ChildFragment? = null
private var rateDialogShown = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.LineChart
import com.github.premnirmal.ticker.base.BaseGraphActivity
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.components.Injector
import com.github.premnirmal.ticker.isNetworkOnline
import com.github.premnirmal.ticker.model.IHistoryProvider.Range
import com.github.premnirmal.ticker.network.data.Quote
Expand All @@ -30,9 +29,7 @@ class GraphActivity : BaseGraphActivity<ActivityGraphBinding>() {
private val viewModel: GraphViewModel by viewModels()
override var range: Range = Range.THREE_MONTH


override fun onCreate(savedInstanceState: Bundle?) {
Injector.appComponent.inject(this)
super.onCreate(savedInstanceState)
setupGraphView()
ticker = checkNotNull(intent.getStringExtra(TICKER))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.view.Surface
import android.view.View
Expand All @@ -24,6 +22,7 @@ import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.github.mikephil.charting.charts.LineChart
import com.github.premnirmal.ticker.AppPreferences
import com.github.premnirmal.ticker.CustomTabs
import com.github.premnirmal.ticker.analytics.Analytics
import com.github.premnirmal.ticker.analytics.ClickEvent
import com.github.premnirmal.ticker.analytics.GeneralEvent
import com.github.premnirmal.ticker.base.BaseGraphActivity
Expand Down Expand Up @@ -66,6 +65,7 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
}

@Inject lateinit var appPreferences: AppPreferences
@Inject lateinit var analytics: Analytics
override val simpleName: String = "NewsFeedActivity"
override val binding: (ActivityQuoteDetailBinding) by viewBinding(ActivityQuoteDetailBinding::inflate)
private lateinit var adapter: NewsFeedAdapter
Expand Down Expand Up @@ -120,7 +120,7 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
binding.appBarLayout.addOnOffsetChangedListener(offsetChangedListener)
} else if (!resources.getBoolean(R.bool.isTablet) && resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
binding.parentView.updateLayoutParams<MarginLayoutParams> {
val rotation = if (VERSION.SDK_INT >= VERSION_CODES.R) {
val rotation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
display?.rotation ?: Surface.ROTATION_90
} else {
windowManager.defaultDisplay.rotation
Expand All @@ -135,11 +135,11 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
setupGraphView()
updateToolbar()
viewModel.quote.observe(this) { result ->
if (result?.wasSuccessful == true) {
if (result.wasSuccessful) {
quote = result.data
fetchNewsAndChartData()
setupQuoteUi()
} else if (result?.wasSuccessful == false) {
} else {
InAppMessage.showMessage(binding.parentView, R.string.error_fetching_stock, error = true)
binding.progress.visibility = View.GONE
binding.graphView.setNoDataText(getString(R.string.error_fetching_stock))
Expand Down Expand Up @@ -206,7 +206,7 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
binding.price.text = quote.priceFormat.format(quote.lastTradePrice)
binding.change.formatChange(quote.change)
binding.changePercent.formatChangePercent(quote.changeInPercent)
updatePositionsUi()
updatePositionsNotesAlertsUi()

binding.positionsHeader.setOnClickListener {
positionOnClickListener()
Expand Down Expand Up @@ -263,14 +263,14 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
} else {
addTickerToWidget(ticker, WidgetDataProvider.INVALID_WIDGET_ID)
}
updatePositionsUi()
updatePositionsNotesAlertsUi()
return@setOnMenuItemClickListener true
}
R.id.action_remove -> {
removeMenuItem.isVisible = false
addMenuItem.isVisible = true
viewModel.removeStock(ticker)
updatePositionsUi()
updatePositionsNotesAlertsUi()
return@setOnMenuItemClickListener true
}
}
Expand Down Expand Up @@ -324,17 +324,17 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
) {
if (requestCode == REQ_EDIT_POSITIONS) {
if (resultCode == Activity.RESULT_OK) {
quote = checkNotNull(data?.getParcelableExtra(AddPositionActivity.QUOTE))
viewModel.loadQuote(ticker)
}
}
if (requestCode == REQ_EDIT_NOTES) {
if (resultCode == Activity.RESULT_OK) {
quote = checkNotNull(data?.getParcelableExtra(AddNotesActivity.QUOTE))
viewModel.loadQuote(ticker)
}
}
if (requestCode == REQ_EDIT_ALERTS) {
if (resultCode == Activity.RESULT_OK) {
quote = checkNotNull(data?.getParcelableExtra(AddAlertsActivity.QUOTE))
viewModel.loadQuote(ticker)
}
}
super.onActivityResult(requestCode, resultCode, data)
Expand All @@ -352,12 +352,12 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
override fun onResume() {
super.onResume()
if (this::quote.isInitialized) {
updatePositionsUi()
updatePositionsNotesAlertsUi()
}
}

@SuppressLint("SetTextI18n")
private fun updatePositionsUi() {
private fun updatePositionsNotesAlertsUi() {
if (!this::quote.isInitialized) {
return
}
Expand All @@ -366,17 +366,17 @@ class QuoteDetailActivity : BaseGraphActivity<ActivityQuoteDetailBinding>(), New
binding.positionsContainer.visibility = View.VISIBLE
binding.positionsHeader.visibility = View.VISIBLE
binding.notesHeader.visibility = View.VISIBLE
binding.notesContainer.visibility = View.VISIBLE
binding.alertHeader.visibility = View.VISIBLE
binding.numShares.text = quote.numSharesString()
binding.equityValue.text = quote.priceFormat.format(quote.holdings())
val notesText = quote.properties?.notes
binding.notesContainer.visibility = View.VISIBLE
if (notesText.isNullOrEmpty()) {
binding.notesContainer.visibility = View.GONE
binding.notesDisplay.text = "--"
} else {
binding.notesContainer.visibility = View.VISIBLE
binding.notesDisplay.text = notesText
}

val alertAbove = quote.getAlertAbove()
val alertBelow = quote.getAlertBelow()
if (alertAbove > 0.0f || alertBelow > 0.0f) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,12 @@ import com.github.premnirmal.ticker.widget.WidgetDataProvider
import com.github.premnirmal.tickerwidget.R
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject

class QuoteDetailViewModel(application: Application) : AndroidViewModel(application) {
Expand All @@ -40,8 +39,8 @@ class QuoteDetailViewModel(application: Application) : AndroidViewModel(applicat
@Inject internal lateinit var historyProvider: IHistoryProvider
@Inject internal lateinit var widgetDataProvider: WidgetDataProvider

private val _quote = MutableStateFlow<FetchResult<Quote>?>(null)
val quote: LiveData<FetchResult<Quote>?>
private val _quote = MutableSharedFlow<FetchResult<Quote>>()
val quote: LiveData<FetchResult<Quote>>
get() = _quote.asLiveData()
private val _data = MutableLiveData<List<DataPoint>>()
val data: LiveData<List<DataPoint>>
Expand All @@ -57,7 +56,7 @@ class QuoteDetailViewModel(application: Application) : AndroidViewModel(applicat
get() = _newsError

val details: Flow<List<QuoteDetail>> = _quote.transform { quote ->
if (quote?.wasSuccessful == true) {
if (quote.wasSuccessful) {
quote.data.run {
val details = mutableListOf<QuoteDetail>()
open?.let {
Expand Down Expand Up @@ -141,13 +140,13 @@ class QuoteDetailViewModel(application: Application) : AndroidViewModel(applicat
Injector.appComponent.inject(this)
}

fun loadQuote(ticker: String) = viewModelScope.launch {
_quote.emit(FetchResult.success(checkNotNull(stocksProvider.getStock(ticker))))
}

fun fetchQuote(ticker: String) {
viewModelScope.launch {
if (_quote.value != null && _quote.value!!.wasSuccessful) {
_quote.emit(_quote.value)
return@launch
}
_quote.value = stocksProvider.fetchStock(ticker)
_quote.emit(stocksProvider.fetchStock(ticker))
}
}

Expand Down
Loading

0 comments on commit 44979c2

Please sign in to comment.