使用compose ,paging3,jsoup实现分页加载双色球开奖数据

本篇文章实现的功能就是在页面上分页加载双色球全部开奖数据,看着很简单,实现起来却很困难,是我低估了它的难度,还是我并不适合做程序员??不过经过多天的努力,最终还是实现了,在此记录一下。
知识来源主要有两个:
1,Jetpack新成员,Paging3从吐槽到真香
2, Github开源项目:NewzCompose
其中,
“1” => LotteryRepository(),LotteryViewModel(),LotteryPagingSource(),LotteryData()
"2" => LotteryActivity(),LotteryCompose()

主要引用到的资源,其中需要注意的是jsoup,使用代理的话会引入失败,需要开vpn或者通过jar包的方式引入

    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha03' // viewModel()
    implementation 'androidx.activity:activity-compose:1.3.0-alpha04' // setContent()
    implementation "androidx.paging:paging-runtime:3.0.0-beta02"
    implementation "androidx.paging:paging-compose:1.0.0-alpha08"
    //jsoup
    implementation 'org.jsoup:jsoup:1.13.1'

LotteryActivity()

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.lazy.LazyColumn
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemsIndexed

class LotteryActivity : ComponentActivity() {

    private val lotteryViewModel: LotteryViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val lazyPagingItems: LazyPagingItems<Lottery> =
                lotteryViewModel.getData().collectAsLazyPagingItems()
            LazyColumn(reverseLayout=true) {
                itemsIndexed(lazyPagingItems) { _, item ->
                    LotteryItem(item!!)
                }
            }
        }
    }
}

LotteryCompose()

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun LotteryItem(lottery: Lottery) {
    Box(
        modifier = Modifier
            .padding(start = 16.dp, top = 8.dp, bottom = 8.dp)
            .clickable(onClick = {})
    ) {
        Row(modifier = Modifier.fillMaxWidth()) {
            Column(
                modifier = Modifier.padding(start = 8.dp)
            ) {
                Text(
                    lottery.code,//开奖号码
                    style = TextStyle(color = Color.Black, fontSize = 16.sp),
                    modifier = Modifier.padding(end = 8.dp),
                    maxLines = 1
                )
            }
            Column(
                modifier = Modifier.padding(start = 8.dp)
            ) {
                Text(
                    lottery.issue,//期号
                    style = TextStyle(color = Color.Black, fontSize = 16.sp),
                    modifier = Modifier.padding(end = 8.dp),
                    maxLines = 1
                )
            }
        }
    }
}

LotteryData()

data class Lottery(
    val code :String,   //开奖号码
    val issue :String,//期号
) : Serializable

LotteryViewModel()

class LotteryViewModel : ViewModel() {
    fun getData(): Flow<PagingData<Lottery>> {
        return LotteryRepository.getPagingData().cachedIn(viewModelScope)
    }
}

LotteryRepository()

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import kotlinx.coroutines.flow.Flow

object LotteryRepository {

    private const val PAGE_SIZE = 50

    fun getPagingData(): Flow<PagingData<Lottery>> {
        return Pager(
            config = PagingConfig(
                pageSize = PAGE_SIZE,
                prefetchDistance = PAGE_SIZE.div(20)
            ),
            pagingSourceFactory = { LotteryPagingSource() }
        ).flow
    }
}

LotteryPagingSource()

import androidx.paging.PagingSource
import androidx.paging.PagingState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.withContext
import love.matrix.lottory004.util.TimeUtils
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements

class LotteryPagingSource : PagingSource<Int, Lottery>() {

    private val year = TimeUtils.nowTime.substring(2, 4).toInt()//取年份最后两位 (2021 => 21)
    private val lotterys = MutableStateFlow<List<Lottery>>(listOf())

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Lottery> {

        val page = params.key ?: year//一个年度的开奖数据为一页
        val lotteryList: MutableList<Lottery> = mutableListOf()

        withContext(Dispatchers.IO) {
            val doc =
                //"https://datachart.500.com/ssq/history/newinc/history.php?start=21001&end=21200"
                Jsoup.connect(TARGET_URL + "?start=${page}001&end=${page}200").get()
            val element: Element = doc.getElementById("tdata")
            val elements: Elements = element.select("tr.t_tr1")
            elements.forEach { item ->
                val aaa: Elements = item.select("td")
                if (!aaa.isNullOrEmpty()) {
                    val bbb = Lottery(
                        code = aaa[1].text() + "," +
                                aaa[2].text() + "," +
                                aaa[3].text() + "," +
                                aaa[4].text() + "," +
                                aaa[5].text() + "," +
                                aaa[6].text() + "  " +
                                aaa[7].text(),
                        issue = aaa[0].text()
                    )
                    lotteryList.add(bbb)
                }
            }
            lotterys.value = lotteryList
        }

        return try {
            //使用了反转LazyColumn(reverseLayout=true),所以向上滑为nextKey
            val prevKey = null
            val nextKey = if (page > 3) page - 1 else null//"3"为2003年,双色球2003年开始的
            LoadResult.Page(
                data = lotterys.value,
                prevKey = prevKey,
                nextKey = nextKey,
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Lottery>): Int? {
        TODO("Not yet implemented")
    }

    companion object {
        const val TARGET_URL =
            "https://datachart.500.com/ssq/history/newinc/history.php"

        const val USER_AGENT =
            "{Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36"

    }
}

TimeUtils()

import android.util.Log
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
object TimeUtils {
    val nowTime: String
        get() {
            val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINESE)
            val date = Date(System.currentTimeMillis())
            return simpleDateFormat.format(date)
        }
}

完成后,感觉这些都是一些模版代码,没什么好说的,所以就不多说什么了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容

  • 文档整理了中国福彩双色球,从第一期(20130101)到20190516,所有开奖号码,中奖人数、中奖金额和销售额...
    清昭_QCao阅读 1,681评论 0 1
  • 夜莺2517阅读 127,720评论 1 9
  • 版本:ios 1.2.1 亮点: 1.app角标可以实时更新天气温度或选择空气质量,建议处女座就不要选了,不然老想...
    我就是沉沉阅读 6,896评论 1 6
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,536评论 28 53
  • 兔子虽然是枚小硕 但学校的硕士四人寝不够 就被分到了博士楼里 两人一间 在学校的最西边 靠山 兔子的室友身体不好 ...
    待业的兔子阅读 2,603评论 2 9