CongrooPsyEl
V2EX  ›  Android

伟大的网友们,来帮帮忙。关于使用 DataStore 的问题

  •  
  •   CongrooPsyEl · Apr 1, 2021 · 13904 views
    This topic created in 2049 days ago, the information mentioned may be changed or developed.

    最近刚好想试一下 DataStore,试着写了个更换语言的功能。

    
    open class BaseActivity : AppCompatActivity() {
    
         override fun attachBaseContext(newBase: Context) {
            lifecycleScope.launch(Dispatchers.Main) {
                var context = newBase
                val language = withContext(Dispatchers.IO) {
                    DataStore.read(context, DataStore.KEY_LANG)
                }
                context = Language.changeLanguage(context, language ?: 
                Language.ZH)
                super.attachBaseContext(context)
            }
        }
    }
    

    之前都是在这用 sp 拿出存储的键值对的,现在换了 DataStore 之后不得不用协程所以就协程上面的样子了。

    然后如果这样写的话是会报这样的错:

    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    

    打了断点看了下,代码走不到 super.attachBaseContext(context)。 万能的网友萌,教教萌新吧~

    8 replies  •  2021-04-02 11:36:46 +08:00
    Still4
    Still4
    Apr 1, 2021
    1
    兄弟你这代码贴一半啊...DataStore 用的哪个版本,Language 是什么包

    你试试自己新起一个工程,贴上这段代码能通过编译么...
    ikas
    ikas
    Apr 1, 2021
    2
    lifecycleScope.launch 之后直接返回了...
    ikas
    ikas
    Apr 1, 2021
    3
    然后当然走不到 super.attachBaseContext(context),所以 context 是 null
    fromzero
    fromzero
    Apr 1, 2021
    4
    lifecycleScope 生命周期问题
    ikas
    ikas
    Apr 1, 2021
    5
    attachBaseContext 这个方法你要保证 super 这个调用之后,才能返回
    fromzero
    fromzero
    Apr 1, 2021
    6
    @fromzero 看错了。我也不不知道
    hstan
    hstan
    Apr 1, 2021
    7
    mmkv 不香吗
    Still4
    Still4
    Apr 2, 2021
    8
    class MyFragment: Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    viewLifecycleOwner.lifecycleScope.launch {
    val params = TextViewCompat.getTextMetricsParams(textView)
    val precomputedText = withContext(Dispatchers.Default) {
    PrecomputedTextCompat.create(longTextContent, params)
    }
    TextViewCompat.setPrecomputedText(textView, precomputedText)
    }
    }
    }

    lifecycleScope 官方用法是这样的,我理解是 lifecycleScope.launch(Dispatchers.Main)这里就有问题
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4476 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 01:14 · PVG 09:14 · LAX 17:14 · JFK 20:14
    ♥ Do have faith in what you're doing.