Skip to content

Commit

Permalink
fix: remove deprecated _instance
Browse files Browse the repository at this point in the history
Closes #3893
  • Loading branch information
VaiTon committed Mar 15, 2021
1 parent a4a0458 commit e738e54
Show file tree
Hide file tree
Showing 26 changed files with 237 additions and 270 deletions.
Expand Up @@ -82,12 +82,6 @@ class OFFApplication : MultiDexApplication(), Configuration.Provider {
private const val DEBUG = false
val LOG_TAG = OFFApplication::class.simpleName!!

@JvmStatic
@Deprecated("Use hilt.")
lateinit var _daoSession: DaoSession
@Synchronized
private set

@Deprecated("Use hilt.")
lateinit var _instance: OFFApplication
@Synchronized
Expand Down

This file was deleted.

This file was deleted.

Expand Up @@ -35,12 +35,14 @@ import androidx.appcompat.app.AppCompatDelegate
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.edit
import androidx.core.content.pm.PackageInfoCompat
import androidx.core.net.toUri
import androidx.preference.*
import androidx.preference.Preference.OnPreferenceClickListener
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.afollestad.materialdialogs.MaterialDialog
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
Expand All @@ -52,7 +54,6 @@ import openfoodfacts.github.scrachx.openfood.AppFlavors.OFF
import openfoodfacts.github.scrachx.openfood.AppFlavors.OPFF
import openfoodfacts.github.scrachx.openfood.AppFlavors.isFlavors
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.app.OFFApplication
import openfoodfacts.github.scrachx.openfood.customtabs.CustomTabActivityHelper
import openfoodfacts.github.scrachx.openfood.customtabs.WebViewFallback
import openfoodfacts.github.scrachx.openfood.features.scan.ContinuousScanActivity
Expand All @@ -75,11 +76,15 @@ import org.greenrobot.greendao.async.AsyncOperation
import org.greenrobot.greendao.async.AsyncOperationListener
import org.greenrobot.greendao.query.WhereCondition.StringCondition
import java.util.*
import javax.inject.Inject


@AndroidEntryPoint
class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnSharedPreferenceChangeListener {
private val disp = CompositeDisposable()

@Inject
lateinit var daoSession: DaoSession

override val navigationDrawerListener: NavigationDrawerListener? by lazy {
if (activity is NavigationDrawerListener) activity as NavigationDrawerListener
else null
Expand Down Expand Up @@ -154,7 +159,7 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
requirePreference<SwitchPreference>(getString(R.string.pref_scanner_type_key)).let {
it.isVisible = ContinuousScanActivity.showSelectScannerPref
it.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
if(newValue == true){
if (newValue == true) {
MaterialDialog.Builder(requireActivity()).run {
title(R.string.preference_choose_scanner_dialog_title)
content(R.string.preference_choose_scanner_dialog_body)
Expand All @@ -165,15 +170,14 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
Toast.makeText(requireActivity(), getString(R.string.changes_saved), Toast.LENGTH_SHORT).show()
}
negativeText(R.string.dialog_cancel)
onNegative {
dialog, _ -> dialog.dismiss()
onNegative { dialog, _ ->
dialog.dismiss()
it.isChecked = false
settings.edit { putBoolean(getString(R.string.pref_scanner_type_key), false) }
}
show()
}
}
else{
} else {
it.isChecked = false
settings.edit { putBoolean(getString(R.string.pref_scanner_type_key), newValue as Boolean) }
Toast.makeText(requireActivity(), getString(R.string.changes_saved), Toast.LENGTH_SHORT).show()
Expand All @@ -182,23 +186,17 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
}
}

val countryLabels = mutableListOf<String>()
val countryTags = mutableListOf<String>()

val countryPreference = requirePreference<ListPreference>(getString(R.string.pref_country_key))

val asyncSessionCountries = OFFApplication._daoSession.startAsyncSession()
val countryNameDao = OFFApplication._daoSession.countryNameDao
val asyncSessionCountries = daoSession.startAsyncSession()
val countryNameDao = daoSession.countryNameDao

// Set query finish listener
asyncSessionCountries.listenerMainThread = AsyncOperationListener { operation: AsyncOperation ->
val countryNames = operation.result as List<CountryName>
countryNames.forEach {
countryLabels.add(it.name)
countryTags.add(it.countyTag)
}
countryPreference.entries = countryLabels.toTypedArray()
countryPreference.entryValues = countryTags.toTypedArray()
countryPreference.entries = countryNames.map { it.name }.toTypedArray()
countryPreference.entryValues = countryNames.map { it.countyTag }.toTypedArray()
}
// Execute query
asyncSessionCountries.queryList(countryNameDao.queryBuilder()
Expand All @@ -213,19 +211,20 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
}

requirePreference<Preference>(getString(R.string.pref_contact_us_key)).setOnPreferenceChangeListener { _, _ ->
val contactIntent = Intent(Intent.ACTION_SENDTO)
contactIntent.data = Uri.parse(getString(R.string.off_mail))
contactIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
try {
startActivity(contactIntent)
startActivity(Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse(getString(R.string.off_mail))
flags = Intent.FLAG_ACTIVITY_NEW_TASK
})
} catch (e: ActivityNotFoundException) {
Toast.makeText(requireActivity(), R.string.email_not_found, Toast.LENGTH_SHORT).show()
}
true
}
requirePreference<Preference>(getString(R.string.pref_rate_us_key)).setOnPreferenceChangeListener { _, _ ->
try {
startActivity(Intent(ACTION_VIEW, Uri.parse("market://details?id=${requireActivity().packageName}")))
startActivity(Intent(ACTION_VIEW,
Uri.parse("market://details?id=${requireActivity().packageName}")))
} catch (e: ActivityNotFoundException) {
startActivity(Intent(ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=${requireActivity().packageName}")))
}
Expand Down Expand Up @@ -287,48 +286,22 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
}

if (isFlavors(OFF, OBF, OPFF)) {
getAnalysisTagConfigs(OFFApplication._daoSession)
getAnalysisTagConfigs(daoSession)
} else {
preferenceScreen.removePreference(preferenceScreen.requirePreference(getString(R.string.pref_key_display)))
}
}
}

private fun buildDisplayCategory(configs: List<AnalysisTagConfig>?) {
private fun buildDisplayCategory(configs: List<AnalysisTagConfig>) {
if (!isAdded) return

val displayCategory = preferenceScreen.requirePreference<PreferenceCategory>(getString(R.string.pref_key_display))
displayCategory.removeAll()
preferenceScreen.addPreference(displayCategory)

// If analysis tag is empty show "Load ingredient detection data" option in order to manually reload taxonomies
if (configs == null || configs.isEmpty()) {
val preference = Preference(preferenceScreen.context)
preference.setTitle(R.string.load_ingredient_detection_data)
preference.setSummary(R.string.load_ingredient_detection_data_summary)
preference.onPreferenceClickListener = OnPreferenceClickListener { pref: Preference ->
pref.onPreferenceClickListener = null
val manager = WorkManager.getInstance(requireContext())
val request = OneTimeWorkRequest.from(LoadTaxonomiesWorker::class.java)

// The service will load server resources only if newer than already downloaded...
manager.enqueue(request)
manager.getWorkInfoByIdLiveData(request.id).observe(this, { workInfo: WorkInfo? ->
if (workInfo != null) {
if (workInfo.state == WorkInfo.State.RUNNING) {
preference.setTitle(R.string.please_wait)
preference.setIcon(R.drawable.ic_cloud_download_black_24dp)
preference.summary = null
preference.widgetLayoutResource = R.layout.loading
} else if (workInfo.state == WorkInfo.State.SUCCEEDED) {
getAnalysisTagConfigs(OFFApplication._daoSession)
}
}
})
true
}
displayCategory.addPreference(preference)
} else {
if (configs.isNotEmpty()) {
configs.forEach { config ->
displayCategory.addPreference(CheckBoxPreference(this.context).apply {
key = config.type
Expand All @@ -339,14 +312,43 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
title = getString(R.string.display_analysis_tag_status, config.typeName.toLowerCase(Locale.getDefault()))
})
}
} else {
val preference = Preference(preferenceScreen.context).apply {
setTitle(R.string.load_ingredient_detection_data)
setSummary(R.string.load_ingredient_detection_data_summary)
onPreferenceClickListener = OnPreferenceClickListener { pref ->
pref.onPreferenceClickListener = null
val request = OneTimeWorkRequest.from(LoadTaxonomiesWorker::class.java)

// The service will load server resources only if newer than already downloaded...
WorkManager.getInstance(requireContext()).let { manager ->
manager.enqueue(request)
manager.getWorkInfoByIdLiveData(request.id).observe(this@PreferencesFragment, { workInfo: WorkInfo? ->
if (workInfo != null) {
if (workInfo.state == WorkInfo.State.RUNNING) {
pref.setTitle(R.string.please_wait)
pref.setIcon(R.drawable.ic_cloud_download_black_24dp)
pref.summary = null
pref.widgetLayoutResource = R.layout.loading
} else if (workInfo.state == WorkInfo.State.SUCCEEDED) {
getAnalysisTagConfigs(daoSession)
}
}
})
}
true
}
}
displayCategory.addPreference(preference)
}
displayCategory.isVisible = true
}

private fun openWebCustomTab(@StringRes resId: Int): Boolean {
val customTabsIntent = CustomTabsIntent.Builder().build()
customTabsIntent.intent.putExtra("android.intent.extra.REFERRER", Uri.parse("android-app://${requireContext().packageName}"))
CustomTabActivityHelper.openCustomTab(requireActivity(), customTabsIntent, Uri.parse(getString(resId)), WebViewFallback())
val customTabsIntent = CustomTabsIntent.Builder().build().apply {
intent.putExtra("android.intent.extra.REFERRER", "android-app://${requireContext().packageName}".toUri())
}
CustomTabActivityHelper.openCustomTab(requireActivity(), customTabsIntent, getString(resId).toUri(), WebViewFallback())
return true
}

Expand Down Expand Up @@ -404,7 +406,7 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem, OnShare
analysisTagConfigs
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { configs -> buildDisplayCategory(configs) }
.subscribe { configs: List<AnalysisTagConfig> -> buildDisplayCategory(configs) }
.addTo(disp)
}

Expand Down
Expand Up @@ -8,25 +8,35 @@ import android.view.Menu
import android.widget.SearchView
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.databinding.ActivityAdditivesExplorerBinding
import openfoodfacts.github.scrachx.openfood.features.listeners.CommonBottomListenerInstaller.installBottomNavigation
import openfoodfacts.github.scrachx.openfood.features.listeners.CommonBottomListenerInstaller.selectNavigationItem
import openfoodfacts.github.scrachx.openfood.features.search.ProductSearchActivity
import openfoodfacts.github.scrachx.openfood.features.shared.BaseActivity
import openfoodfacts.github.scrachx.openfood.models.DaoSession
import openfoodfacts.github.scrachx.openfood.models.entities.additive.AdditiveName
import openfoodfacts.github.scrachx.openfood.models.entities.additive.AdditiveNameDao
import openfoodfacts.github.scrachx.openfood.utils.LocaleHelper
import openfoodfacts.github.scrachx.openfood.utils.SearchType
import openfoodfacts.github.scrachx.openfood.utils.Utils
import org.greenrobot.greendao.async.AsyncOperation
import org.greenrobot.greendao.async.AsyncOperationListener
import java.util.*
import javax.inject.Inject

@AndroidEntryPoint
class AdditiveListActivity : BaseActivity() {
private var _binding: ActivityAdditivesExplorerBinding? = null
private val binding get() = _binding!!

@Inject
lateinit var daoSession: DaoSession


private var additives = mutableListOf<AdditiveName>()


override fun onDestroy() {
super.onDestroy()
_binding = null
Expand All @@ -39,7 +49,6 @@ class AdditiveListActivity : BaseActivity() {
setSupportActionBar(binding.toolbarInclude.toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setTitle(R.string.additives)
val daoSession = Utils.daoSession
val asyncSessionAdditives = daoSession.startAsyncSession()
val additiveNameDao = daoSession.additiveNameDao
val languageCode = LocaleHelper.getLanguage(this)
Expand Down
Expand Up @@ -43,13 +43,13 @@ import openfoodfacts.github.scrachx.openfood.AppFlavors.OPF
import openfoodfacts.github.scrachx.openfood.AppFlavors.OPFF
import openfoodfacts.github.scrachx.openfood.AppFlavors.isFlavors
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.app.OFFApplication
import openfoodfacts.github.scrachx.openfood.databinding.ActivityEditProductBinding
import openfoodfacts.github.scrachx.openfood.features.product.ProductFragmentPagerAdapter
import openfoodfacts.github.scrachx.openfood.features.product.edit.overview.ProductEditOverviewFragment
import openfoodfacts.github.scrachx.openfood.images.IMG_ID
import openfoodfacts.github.scrachx.openfood.images.ProductImage
import openfoodfacts.github.scrachx.openfood.jobs.OfflineProductWorker.Companion.scheduleSync
import openfoodfacts.github.scrachx.openfood.models.DaoSession
import openfoodfacts.github.scrachx.openfood.models.Product
import openfoodfacts.github.scrachx.openfood.models.ProductImageField
import openfoodfacts.github.scrachx.openfood.models.entities.OfflineSavedProduct
Expand All @@ -59,7 +59,6 @@ import openfoodfacts.github.scrachx.openfood.network.CommonApiManager.productsAp
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient.Companion.addToHistorySync
import openfoodfacts.github.scrachx.openfood.utils.OfflineProductService
import openfoodfacts.github.scrachx.openfood.utils.Utils.daoSession
import openfoodfacts.github.scrachx.openfood.utils.Utils.hideKeyboard
import openfoodfacts.github.scrachx.openfood.utils.Utils.isExternalStorageWritable
import openfoodfacts.github.scrachx.openfood.utils.getLoginPreferences
Expand All @@ -80,6 +79,12 @@ class ProductEditActivity : AppCompatActivity() {
@Inject
lateinit var offlineService: OfflineProductService

@Inject
lateinit var daoSession: DaoSession

@Inject
lateinit var client: OpenFoodAPIClient

private val addProductPhotosFragment = ProductEditPhotosFragment()
private val nutritionFactsFragment = ProductEditNutritionFactsFragment()
private val ingredientsFragment = ProductEditIngredientsFragment()
Expand Down Expand Up @@ -258,7 +263,7 @@ class ProductEditActivity : AppCompatActivity() {
imgMap[ApiFields.Keys.USER_ID] = createTextPlain(login)
imgMap[ApiFields.Keys.USER_PASS] = createTextPlain(password)
}
imgMap[ApiFields.Keys.USER_COMMENT] = createTextPlain(OpenFoodAPIClient.getCommentToUpload(login))
imgMap[ApiFields.Keys.USER_COMMENT] = createTextPlain(client.getCommentToUpload(login))
}

private fun saveProduct() {
Expand Down Expand Up @@ -392,7 +397,7 @@ class ProductEditActivity : AppCompatActivity() {
} else {
hideImageProgress(position, true, it.message ?: "Empty error.")
Log.i(this::class.simpleName, it.message ?: "Empty error.")
Toast.makeText(OFFApplication._instance, it.message, Toast.LENGTH_SHORT).show()
Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
}
}
.subscribe { jsonNode ->
Expand Down
Expand Up @@ -63,6 +63,9 @@ class ProductEditIngredientsFragment : ProductEditFragment() {
private var _binding: FragmentAddProductIngredientsBinding? = null
private val binding get() = _binding!!

@Inject
lateinit var daoSession: DaoSession

private var photoReceiverHandler: PhotoReceiverHandler? = null
private var mAllergenNameDao: AllergenNameDao? = null
private var photoFile: File? = null
Expand Down Expand Up @@ -110,7 +113,7 @@ class ProductEditIngredientsFragment : ProductEditFragment() {

val bundle = arguments
if (bundle != null) {
mAllergenNameDao = Utils.daoSession.allergenNameDao
mAllergenNameDao = daoSession.allergenNameDao
product = getProductFromArgs()
mOfflineSavedProduct = getEditOfflineProductFromArgs()
if (product != null) {
Expand Down Expand Up @@ -273,8 +276,6 @@ class ProductEditIngredientsFragment : ProductEditFragment() {
/**
* Automatically load suggestions for allergen names
*/
@Inject
lateinit var daoSession: DaoSession
private fun loadAutoSuggestions() {
val asyncSessionAllergens = daoSession.startAsyncSession()
val allergenNameDao = daoSession.allergenNameDao
Expand Down

0 comments on commit e738e54

Please sign in to comment.