小编SNM*_*SNM的帖子

不能使用 liveData 或 viewModelScope.launch

我试图在我的应用程序中将这两个构建器用于协程,但在我的 ViewModel 中我无法导入它们或者它们不会弹出。

这些是我的依赖项:

   implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-rc02"

   implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
Run Code Online (Sandbox Code Playgroud)

在我的 ViewModel 中

class MainViewModel(): ViewModel() {

init{

  viewModelScope ----> does not work , marked in red
  val data = liveData {} ----> does not work, marked in red
}


}
Run Code Online (Sandbox Code Playgroud)

我使用无效的缓存重建、清理和重新启动,但我无法使用它们

android mvvm kotlin kotlin-coroutines

5
推荐指数
1
解决办法
1991
查看次数

挂起函数只能在协程体内调用

我正在尝试使用 Kotlin Flows 和 Firebase 为我的视图提供实时更新。

这就是我从我的ViewModel以下收集实时数据的方式:

class MainViewModel(repo: IRepo): ViewModel() {

    val fetchVersionCode = liveData(Dispatchers.IO) {
        emit(Resource.Loading())

        try {
            repo.getVersionCode().collect {
                emit(it)
            }

        } catch (e: Exception){
            emit(Resource.Failure(e))
            Log.e("ERROR:", e.message)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是每当 Firebase 中的值发生变化时我从我的存储库中发出每个数据流的方式:

class RepoImpl: IRepo {

    override suspend fun getVersionCodeRepo(): Flow<Resource<Int>> = flow {

        FirebaseFirestore.getInstance()
            .collection("params").document("app").addSnapshotListener { documentSnapshot, firebaseFirestoreException ->
                val versionCode = documentSnapshot!!.getLong("version")
                emit(Resource.Success(versionCode!!.toInt()))
            }
    }
Run Code Online (Sandbox Code Playgroud)

问题是,当我使用:

 emit(Resource.Success(versionCode!!.toInt()))
Run Code Online (Sandbox Code Playgroud)

Android Studio 突出显示了发出调用:

挂起函数“emit”只能从协程或其他挂起函数调用

但是我从CoroutineScope我的ViewModel.

这里有什么问题?

谢谢

android kotlin firebase kotlin-coroutines kotlinx.coroutines.flow

5
推荐指数
2
解决办法
4596
查看次数

导航组件 - onSupportNavigateUp()

真的有必要打电话吗

override fun onSupportNavigateUp() = findNavController(R.id.nav_host_fragment).navigateUp()
Run Code Online (Sandbox Code Playgroud)

在我的 MainActivity 中?

因为当我在我的 xml 中附加 NavHostFragment 时,它从那里开始,但是我看过 Google I/O 讲座,他们使用它来作为导航的起点

我的问题

哪里有必要使用它?

谢谢

android android-fragments kotlin android-navigation android-architecture-navigation

4
推荐指数
1
解决办法
5163
查看次数

将多种样式应用于单个文本 - Jetpack Compose

我想知道有没有办法给一个文本应用多种样式,这里我给这个文本应用了一个材质主题,但是我也想改变这个文本大小,我该怎么做?因为我已经使用了 style 属性

    Text(text = "This is my default text", style = (MaterialTheme.typography).body1)
Run Code Online (Sandbox Code Playgroud)

另外,如何添加 2 个修饰符,假设我想添加填充和一个 fillMaxWidth

android kotlin android-jetpack android-jetpack-compose

4
推荐指数
1
解决办法
1516
查看次数

弹出片段时未清除 SharedViewModel

我正在使用像这里这样的共享视图模型

但问题是,当我清除最后一个片段时,我想清除视图模型,或者杀死它的实例,但是当我离开使用它的最后一个片段时,它以某种方式幸存下来

如何以编程方式清除此视图模型?

我像这样使用它

片段A

private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated() {

     model.getTotal().observe(viewLifecycleOwner, Observer { cartTotal ->
                total = cartTotal
            })

    }
Run Code Online (Sandbox Code Playgroud)

从片段 BI 发送的总数

Fragment B

private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated() {

     model.setTotal = 10
}
Run Code Online (Sandbox Code Playgroud)

But when leaving Fragment A with that data (doing popBackStack since I'm using navigation components) it does not clear the viewmodel, instead when I open again my fragment , the data stills there

I …

android android-fragments kotlin android-viewmodel android-architecture-navigation

3
推荐指数
1
解决办法
1048
查看次数

来自 viewpager2 和我的父 Fragment 的 SharedViewModel

所以,我有一个片段,我们称之为片段 A,我需要它作为我的共享视图模型的主要宿主。

所以我有这样的

class FragmentA:Fragment() {

 private val model: SharedViewModel by viewModels()

}
Run Code Online (Sandbox Code Playgroud)

现在,在片段 A 中,我设置了 viewpager2 Adapter

private fun setupViewPagerWithTabLayout(
        productList: MutableList<Producto>,
        drinkList: MutableList<Producto>
    ) {
        val fragmentList = listOf(
            FragmentProducts.newInstance(productList),
            FragmentProducts.newInstance(drinkList))

        viewPager2.adapter = MyViewPageAdapter(requireActivity(),fragmentList)
        val tabLayoutMediator = TabLayoutMediator(tabLayout, viewPager2,
            TabLayoutMediator.TabConfigurationStrategy { tab, position ->

                when (position) {
                    0 -> {
                        tab.text = "Option1"
                    }
                    1 -> {
                        tab.text = "Option2"
                    }
                }

            })
        tabLayoutMediator.attach()
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我实例化了位于 viewpager 中的 Fragment A 内的 FragmentProduct,但我的适配器需要 FragmentActivity

class MyViewPageAdapter(fragmentActivity: FragmentActivity,private val fragmentList: …
Run Code Online (Sandbox Code Playgroud)

android android-fragments android-viewpager kotlin android-architecture-navigation

3
推荐指数
1
解决办法
1831
查看次数

当我从一个片段返回到另一个片段时,我的观察者总是会开火

我正在使用导航组件,我有Fragment AFragment B,从Fragment A我使用安全参数将一个对象发送到Fragment B并导航到它。

override fun onSelectableItemClick(position:Int,product:Product) {
        val action = StoreFragmentDirections.actionNavigationStoreToOptionsSelectFragment(product,position)
        findNavController().navigate(action)
    }
Run Code Online (Sandbox Code Playgroud)

现在,在我的Fragment B中进行一些逻辑之后,我想再次将该数据传递给我使用的Fragment A

  btn_add_to_cart.setOnClickListener {button ->     
 findNavController().previousBackStackEntry?.savedStateHandle?.set("optionList",Pair(result,product_position))
                findNavController().popBackStack()
            }
Run Code Online (Sandbox Code Playgroud)

然后在片段 A中,我用

findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Pair<MutableList<ProductOptions>,Int>>("optionList")
            ?.observe(viewLifecycleOwner, Observer {
                storeAdapter.updateProductOptions(it.second,it.first)
            })
Run Code Online (Sandbox Code Playgroud)

现在,这工作正常,但如果我从片段 A转到片段 B并按后退按钮,上面的观察者会再次触发,复制我当前的数据,有没有办法在我只按下片段btn_add_to_cart中的按钮时触发该观察者

android android-fragments kotlin android-viewmodel android-architecture-navigation

3
推荐指数
1
解决办法
3277
查看次数

Drawable not beign fond in kotlin file

I'm trying to access a drawable resource from a non Activity class, this is because I want to have my composable function in another file rather than having it in the main file, the thing is that from the Main file I can access R.drawable.header , but from the other crated file I cant

在此输入图像描述

import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumnFor
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.unit.dp …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-recyclerview android-jetpack-compose

3
推荐指数
1
解决办法
623
查看次数

OutlineTextField 、 TextField 在 Jetpack Compose 1.0.0-alpha02 中不起作用

由于某种原因,CoreTextField 可以工作,但 TextField 和 OutlineTextField 不能

作品

@Composable
fun TextFieldDemo(){
    val text = remember { mutableStateOf(TextFieldValue("Text")) }
    CoreTextField(modifier = Modifier.fillMaxWidth(),
            value = text.value,
            onValueChange = {text.value = it})
}
Run Code Online (Sandbox Code Playgroud)

不工作

    @Composable
fun TextFieldDemo(){
    val text = remember { mutableStateOf(TextFieldValue("Text")) }
    OutlinedTextField(value = text.value,
            onValueChange = {text.value = it}, label = {Text("Test")})
}
Run Code Online (Sandbox Code Playgroud)

错误:无法调用以下函数OutlinedTextField

从文档更改

Bug Fixes

androidx.ui.foundation.TextFieldValue and androidx.ui.input.EditorValue are deprecated. TextField, FilledTextField and CoreTextField composables that uses that type is also deprecated. Please use androidx.ui.input.TextFieldValue instead (I4066d, b/155211005) …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-jetpack-compose

3
推荐指数
1
解决办法
1万
查看次数

获取时间戳大于 24 小时的文档

所以,我试图只获取 24 小时前的文档,我在我的数据库中保存了一个时间戳值作为时间戳

data class Order(@ServerTimestamp val timestamp:Date? = null)
Run Code Online (Sandbox Code Playgroud)

现在,当我查询时,我想带回时间戳大于 24 小时但查询不成功的文档,我已在控制台检查并创建了所有查询

suspend fun getIncompletedOrders(): Resource<List<Order>> {
        val reminderList = mutableListOf<Order>()
        val oneDay = Date().time + (24 * 60 * 60 * 1000)
        val query = FirebaseFirestore.getInstance()
            .collection("orders")
            .whereEqualTo("uid",FirebaseAuth.getInstance().currentUser?.uid)
            .whereIn("status", listOf(1,2,4,5,6))
            .whereGreaterThan("timestamp",oneDay)
            .get().await()
        for(document in query.documents){
            reminderList.add(document.toObject(Order::class.java)!!)
        }
        return Resource.Success(reminderList)
    }
Run Code Online (Sandbox Code Playgroud)

正如您在此处看到的,我获取当前时间,向其中添加 24 小时并检查存储在 Firebase 中的时间戳是否大于该时间,但是当我在 Firestore 中将时间戳更改为前一天时,我没有收到任何文件,是什么发生?

在此处输入图片说明

android kotlin firebase google-cloud-firestore

0
推荐指数
1
解决办法
766
查看次数

InvalidUrlError:无法识别的方案“gs”

因此,我尝试从另一个项目授予对存储桶的访问权限,以便将该存储桶的数据导入到项目中,我使用了文档建议的命令

https://firebase.google.com/docs/firestore/manage-data/move-data#move_data_files_to_a_local_bucket

gsutil iam ch serviceAccount:[DESTINATION_PROJECT_ID]@appspot.gserviceaccount.com:admin \
gs://[SOURCE_BUCKET]
Run Code Online (Sandbox Code Playgroud)

但当我使用它时

在此输入图像描述

是只有我一个人还是 Google Cloud Platform 文档在某些方面总是很模糊?

谢谢

google-cloud-storage firebase google-cloud-platform google-cloud-firestore

0
推荐指数
1
解决办法
3925
查看次数

当我对它加号时,我的 Set 没有添加任何元素

我正在制作一个功能,您可以选择多个组,然后根据所选的组进行查询,但我的问题是我创建了一个将存储组 ID 的 Set,目前调试器只是逐步执行每个加和减到集合中,但是当我到达最后一个调试点时集合仍然是空的,这是我的代码

 class GroupsAdapter(private val context: Context,private val groupList:List<Group>,val itemClickListener:OnCheckBoxClicked):BaseAdapter() {

    private var selectedGroups:Set<String> = hashSetOf()

    interface OnCheckBoxClicked{
        fun onGroupCheckBoxClick(group:Group,selectedGroups:Set<String>)
    }

    override fun getView(position: Int, p1: View?, p2: ViewGroup?): View {
        val group = groupList[position]
        val view = LayoutInflater.from(context).inflate(R.layout.group_spinner_layout,p2,false)

        if(position == 0){
            group.isChecked = true
            view.group_checkbox.isChecked = group.isChecked
        }
        view.txt_group_name.text = group.group_name
        view.group_checkbox.isChecked = group.isChecked

        view.group_checkbox.setOnCheckedChangeListener { compoundButton, isChecked ->
            group.isChecked = isChecked

            if(group.isChecked){
                selectedGroups.plus(group.group_id)
            }else{
                selectedGroups.minus(group.group_id)
            }

            view.group_checkbox.isChecked = group.isChecked
            itemClickListener.onGroupCheckBoxClick(group,selectedGroups)
        }
        return view
    }

    override fun …
Run Code Online (Sandbox Code Playgroud)

android list set kotlin

0
推荐指数
1
解决办法
42
查看次数