How to use Android Jetpack Paging 3 with PHP
Get the solution ↓↓↓I have succesfully implemented Android Pagination Library in my App, The problem is - I dont know the proper way to use it with my PHP code as BackEnd with regards to number of items to load etc.
get_feed.php
<?php
$limit = 2;
//find out how many rows are in the table
$sql = "SELECT count(*) FROM uploads";
$result = $conn->prepare($sql);
$result->execute();
$total = $result->fetchColumn();
//total pages
$totalpages = ceil($total/$limit);
//get the current page or set a default
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
// cast var as int
(int) $currentpage = $_GET['page'];
} else {
//default page num
$currentpage = 1;
}
//if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
//the offset of the list, based on current page
$offset = ($currentpage - 1) * $limit;
$stmt = "SELECT * FROM uploads ORDER by id DESC LIMIT $offset, $limit";
//I get all requiresd data, send and encode in json
echo json_encode($obj);
?>
All I want to do from this PHP code is to load 2 items at a time from the database.
Android codes
ApiService.kt
@GET(EndPoints.GET_RANDOM_FEED)
suspend fun getRandomFeed(
@Query("page") page: Int
) : PostsResponse
FeedSource.kt
class FeedSource(private val apiDataSource: ApiDataSource) : PagingSource<Int, Posts>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Posts> {
return try {
//start from page 1 for undefined
val nextPage = params.key ?: 1
val response = apiDataSource.getRandomFeed(nextPage)
LoadResult.Page(
data = response.feeds,
prevKey = if (nextPage == 1) null else nextPage - 1,
nextKey = nextPage.plus(1)
)
} catch (e: Exception){
LoadResult.Error(e)
}
}
}
FeedViewModel.kt
@Singleton
class FeedViewModel constructor(private val apiDataSource: ApiDataSource) : ViewModel() {
//I want to load 10 items at first
val feeds = Pager(PagingConfig(pageSize = 10)) {
FeedSource(apiDataSource)
}.flow.cachedIn(viewModelScope)
}
As it is, All items are loaded at once. I have set up the loadState Adapter which should only show a spinner when items are loading or error as the case may be. But right now, the spinner only shows when all item has been loaded and throws a HTTP 429 error
How do I make the app load 10 items initialy, then 2 at a time according to my PHP code?
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: to enable extensions, verify that they are enabled in your .ini files
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.