【问题标题】:progress bar loading not showing response from server?进度条加载不显示服务器的响应?
【发布时间】:2020-09-18 18:54:49
【问题描述】:

我正在开发新闻应用,但 TopHeadlinesFragment 加载进度条未显示来自服务器的响应 我想知道我在哪里犯了错误我必须做什么才能显示来自服务器的响应。也许我在 topHeadlinesFragment.kt 或 koin 网络模块中的观察者有问题

在我的应用截图下方

loading progress

在我的 TopHeadlinesFragment.kt 下方

class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding
    private val viewModel by viewModel<MainViewModel>()


    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
    // private val newsRepository: NewsRepository by inject()


    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
      //  loadingAds()


    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()

                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.VISIBLE else View.GONE
                    })
                }
                is Results.Failure -> {
                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.INVISIBLE else View.GONE
                })
            }


        }

        viewModel.loadNews()
    })



    }


    }

在 NewsRepository.kt 下方

class NewsRepository(
    private val sportNewsApi: SportNewsInterface,
    private val sportNewsDao: SportNewsDao
) {


    companion object{
        const val  TAG=  "Error"
    }

    val data = sportNewsDao.getAllData()

    suspend fun refresh() = withContext(Dispatchers.IO) {
        val articles = sportNewsApi.getNewsAsync().body()?.articles
        if (articles != null) {
            sportNewsDao.addAll(articles)
          Log.e(TAG,"Error")
            Results.Success(articles)
        } else {
            Results.Failure("MyError")
        }
    }
}

在我的 MainViewModel.kt 下方

class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()

    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    private val _showLoading = MutableLiveData<Boolean>()
    private val _sportList = MutableLiveData<Results>()

    val showLoading: LiveData<Boolean>
        get() = _showLoading

    val sportList: LiveData<Results>
        get() = _sportList


    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        _showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result =  newsRepository.refresh()
            _sportList.value = result
            _showLoading.value = false
        }
    }

    override fun onCleared() {
        job.cancel()
    }

}

在我的 KoinNetworkModule.kt 下方

const val BASE_URL = "https://newsapi.org/"
val netModule = module {


    single {
        createWebService<SportNewsInterface>(
            okHttpClient = createHttpClient(),
            factory = RxJava2CallAdapterFactory.create(),
            baseUrl = BASE_URL
        )
    }
}

/* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
fun createHttpClient(): OkHttpClient {
    val client = OkHttpClient.Builder()
    client.readTimeout(5 * 60, TimeUnit.SECONDS)
    return client.addInterceptor {
        val original = it.request()
        val requestBuilder = original.newBuilder()
        requestBuilder.header("Content-Type", "application/json")
        val request = requestBuilder.method(original.method, original.body).build()
        return@addInterceptor it.proceed(request)
    }.build()
}

/* function to build our Retrofit service */
inline fun <reified T> createWebService(
    okHttpClient: OkHttpClient,
    factory: CallAdapter.Factory, baseUrl: String
): T {
    val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addCallAdapterFactory(factory)
        .client(okHttpClient)
        .build()
    return retrofit.create(T::class.java)
}

【问题讨论】:

  • 回收站视图的可见性如何?它在布局中是否始终可见?响应后您的进度条是否隐藏?
  • 嗨,Antonio 数据根本没有显示只有进度条加载我认为响应问题或存储库或 MainViewModel.kt 有问题我已经检查过您的建议并将断点数据放在那里

标签: android kotlin mvvm android-progressbar kotlin-coroutines


【解决方案1】:

有你的问题。如果您真的想显示响应,无论您得到什么,都可以在改造实例中使用此代码。 Intercepter 的作用是在 Log 级别显示请求和响应。您可以在 Log 窗口中找到 API、Request 和 Resonse 的 URL。

现在像这样修改 KoinNetworkModule.kt

            const val BASE_URL = "https://newsapi.org/"
            val netModule = module {


                single {
                    createWebService<SportNewsInterface>(
                        okHttpClient = createHttpClient(),
                        factory = RxJava2CallAdapterFactory.create(),
                        baseUrl = BASE_URL
                    )
                }
            }

            /* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
            fun createHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val client1 = OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .writeTimeout(2, TimeUnit.MINUTES) // write timeout
            .readTimeout(2, TimeUnit.MINUTES) // read timeout

            .addInterceptor(interceptor)
            .build()

            /* function to build our Retrofit service */
            inline fun <reified T> createWebService(
                okHttpClient: OkHttpClient,
                factory: CallAdapter.Factory, baseUrl: String
            ): T {



                val retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .addCallAdapterFactory(factory)
                    .client(client1)
                    .build()
                return retrofit.create(T::class.java)
            }

【讨论】:

  • 嗨 Pawen 也许你认为我的问题与改造有关
  • 我在那里使用过 koin network modele 也许你需要网络类
  • 是的。在网络课中你必须使用这个.. @EdgarShvedskiy
  • 嗨 Pawen Soni,我已经发布了 KoinNetworkModule,你可以检查一下吗
  • 现在请检查我的答案。您可以使用相同的代码。修改了你的代码。
【解决方案2】:

我通过以下更改我的代码解决了问题。

 private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()
                }
            }
        })

        viewModel.showLoading.observe(this, Observer { showLoading ->
            pb.visibility = if (showLoading) View.VISIBLE else View.GONE
        })

        viewModel.loadNews()
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2012-09-10
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多