refresh data in a Firestore Paging Adapter using Swipe Refresh Layout - android

I am using FirestorePagingAdapter to show data in my app but when I use Swipe Refresh Layout did not work with FirestorePagingAdapter, swipe refresh layout.isVisible = true in LOAD_MORE when I don't scroll
how to work with a Swipe Refresh Layout in FirestorePagingAdapter?
ViewHolde.class:
class ViewHolde(item: View) : RecyclerView.ViewHolder(item){
val username = item.findViewById(R.id.iduser) as TextView
val title = item.findViewById(R.id.idtitle) as TextView
val decription = item.findViewById(R.id.iddes) as TextView
}
User.class:
class User {
lateinit var userphoto: StorageReference
lateinit var username:String
lateinit var title:String
lateinit var notes: String
lateinit var id: String
var isSelected:Boolean = false
constructor(){
}
constructor( id: String?,username:String?,title: String?, notes: String?) {
this.title= title!!
this.id= id!!
this.username= username!!
this.notes= notes!!
}
}
RecyclerActivity.class:
class RecyclerActivity : AppCompatActivity(),SwipeRefreshLayout.OnRefreshListener {
var mylist=ArrayList<User>()
var rv:RecyclerView? = null
var currentuser = FirebaseAuth.getInstance().currentUser!!.uid
val str= FirebaseStorage.getInstance().reference
private var mAuthStateListener: FirebaseAuth.AuthStateListener? = null
var db = FirebaseFirestore.getInstance();
private val notebookRef2 = db.collection("ProfileData")
private val mQuery = notebookRef2.orderBy("title", Query.Direction.ASCENDING)
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(2)
.setPageSize(6)
.build()
val options = FirestorePagingOptions.Builder<User>()
.setLifecycleOwner(this)
.setQuery(mQuery, config, User::class.java)
.build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler)
rec()
var swipeContainer = findViewById(R.id.swipeContainer)as SwipeRefreshLayout
swipeContainer.setOnRefreshListener(this);
swipeContainer = findViewById(R.id.swipeContainer)as SwipeRefreshLayout
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeContainer.setOnRefreshListener {
rv?.invalidate();
swipeContainer.setRefreshing(false);
}
}
override fun onRefresh() {
Handler().postDelayed( Runnable() {
swipeContainer.setRefreshing(false);
}, 3000);
}
fun rec(){
rv=findViewById(R.id.idrecycler) as? RecyclerView
rv!!.setHasFixedSize(true)
rv!!.layoutManager = LinearLayoutManager(this)
db.collection("ProfileData").orderBy("title", Query.Direction.DESCENDING)
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
if (querySnapshot != null) {
for(da in querySnapshot) {
val note = da.toObject(Note::class.java)
var title = note.title
var description = note.notes
var username = note!!.username
var id = note!!.id
mylist.add(User(id!!,username!!, title!!, description!!))
}
}
}
setupadapter()
}
fun setupadapter(){
rv=findViewById(R.id.idrecycler) as? RecyclerView
var mAdapter = object : FirestorePagingAdapter<User, ViewHolde>(options) {
override fun onLoadingStateChanged(state: LoadingState) {
swipeRefreshLayout2.isVisible = false
when (state) {
LoadingState.LOADING_INITIAL -> {
swipeRefreshLayout2.isVisible = true
}
LoadingState.LOADING_MORE -> {
swipeRefreshLayout.isVisible = true
}
LoadingState.LOADED -> {
swipeRefreshLayout.isVisible = false
}
LoadingState.ERROR -> {
swipeRefreshLayout.isVisible = false
}
LoadingState.FINISHED -> {
swipeRefreshLayout.isVisible = false
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolde {
var v = LayoutInflater.from(parent.context)
.inflate(R.layout.iktem_list, parent, false)
return ViewHolde(v)
}
override fun onBindViewHolder(holder: ViewHolde, position: Int, p2: User) {
holder.username.text = mylist.get(position).username
holder.title.text = mylist.get(position).title
holder.decription.text = mylist.get(position).notes
}
}
rv!!.adapter = mAdapter
}
}
ActivityRecycler.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/iddrawer2"
tools:context=".RecyclerActivity">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_height="match_parent"
android:layout_width="match_parent" >
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#4C00CF"
android:id="#+id/idtoolbar2"
tools:ignore="MissingConstraints"/>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:layout_height="460dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idrecycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</ScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<ProgressBar
android:id="#+id/swipeRefreshLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="340dp"
android:visibility="gone"
/>
<ProgressBar
android:id="#+id/swipeRefreshLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="450dp"
android:visibility="gone"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:headerLayout="#layout/header"
android:id="#+id/idnavigatuonv2"
android:layout_gravity="start"
app:menu="#menu/draw_menu"/>
</androidx.drawerlayout.widget.DrawerLayout >

So I'm using the adapter to show transaction history and I have a button to show the filtered transaction history which has status == success.
On button click, I'm updating the adapter the following way:
baseQuery = firestore.collection("transactions")
.whereEqualTo("status", "success")
.orderBy("__name__", Query.Direction.DESCENDING);
options = new FirestorePagingOptions.Builder<ItemTxn>()
.setLifecycleOwner(this)
.setQuery(baseQuery, config, ItemTxn.class)
.build();
adapter.updateOptions(options);
https://github.com/firebase/FirebaseUI-Android/issues/1726#issuecomment-573033035

Related

Create a popup menu with edit/delete functions using recycler view

So I want to make a function which opens a popup menu using Recycler view, I've got the card and icons ready but im not sure how to implement into my
StudentAdapter.kt class.
Im new to Kotlin so popup windows are new to me.
I have the code to edit/delete but first of all how do I get the popup menu to work in my recyclerview?
card_items_rec (row for recyclerview)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:padding="1dp"
android:layout_margin="1dp"
android:weightSum="1">
<TextView
android:id="#+id/tvId"
android:layout_width="wrap_content"
android:layout_height="1dp"
tools:text="Id"
tools:visibility="invisible"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:textAlignment="center"
android:textSize="17dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/tvBuyAmount"
app:layout_constraintHorizontal_bias="0.135"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.533"
tools:text="Date" />
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="4dp"
android:textAlignment="center"
android:textSize="17dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/tvBuyAmount"
app:layout_constraintHorizontal_bias="0.94"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Name" />
<TextView
android:id="#+id/tvBuyAmount"
android:layout_width="59dp"
android:layout_height="wrap_content"
android:padding="7dp"
android:textAlignment="center"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/tvUseAmount"
app:layout_constraintHorizontal_bias="0.885"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="aaa" />
<TextView
android:id="#+id/tvUseAmount"
android:layout_width="49dp"
android:layout_height="wrap_content"
android:layout_marginStart="248dp"
android:padding="7dp"
android:textAlignment="center"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/deleteBtn"
app:layout_constraintHorizontal_bias="0.269"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="aaa" />
<ImageView
android:id="#+id/popupButton"
android:layout_width="67dp"
android:layout_height="28dp"
android:layout_marginStart="28dp"
android:src="#drawable/ic_menu_more"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="#+id/tvUseAmount"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/deleteBtn"
android:layout_width="67dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="削除"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.982"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
show_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/editText"
android:title="編集"
android:icon="#drawable/ic_edit" />
<item
android:id="#+id/delete"
android:title="削除"
android:icon="#drawable/ic_delete" />
</menu>
Student.adapter.kt
class StudentAdapter: RecyclerView.Adapter<StudentAdapter.StudentViewHolder>() {
private var stdList: ArrayList<StudentModel> = ArrayList()
private var onClickItem: ((StudentModel) -> Unit)?=null
private var onClickDeleteItem: ((StudentModel) -> Unit)?=null
fun addItems(items: ArrayList<StudentModel>){
this.stdList=items
notifyDataSetChanged()
}
fun setOnClickItem(callback:(StudentModel)->Unit){
this.onClickItem = callback
}
fun setOnClickDeleteItem(callback: (StudentModel) -> Unit){
this.onClickDeleteItem = callback
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)= StudentViewHolder (
LayoutInflater.from(parent.context).inflate(R.layout.card_items_rec,parent,false)
)
override fun onBindViewHolder(holder: StudentViewHolder, position: Int) {
val std = stdList[position]
holder.bindView(std)
holder.itemView.setOnClickListener{onClickItem?.invoke(std)}
holder.btnDelete.setOnClickListener{onClickDeleteItem?.invoke(std)}
}
override fun getItemCount(): Int {
return stdList.size
}
class StudentViewHolder(var view: View):RecyclerView.ViewHolder(view){
var id:TextView = view.findViewById<TextView>(R.id.tvId)
var name:TextView = view.findViewById<TextView>(R.id.tvName)
var email:TextView = view.findViewById<TextView>(R.id.tvEmail)
var buyAmount:TextView = view.findViewById<TextView>(R.id.tvBuyAmount)
var useAmount:TextView = view.findViewById<TextView>(R.id.tvUseAmount)
var btnDelete:Button = view.findViewById<Button>(R.id.deleteBtn)
var popupButton: ImageView = view.findViewById(R.id.popupButton)
fun bindView(std:StudentModel){
id.text = std.id.toString()
name.text = std.name
email.text = std.email
buyAmount.text = std.buyamount.toString()
useAmount.text = std.useamount.toString()
}
}
}
allRecordPage.kt
class allRecordpage : AppCompatActivity() {
private lateinit var edName: EditText
private lateinit var edEmail: Button
private lateinit var edBuyAmount: EditText
private lateinit var edUseAmount: EditText
private lateinit var edReason: EditText
private lateinit var btnAdd: Button
private lateinit var btnView: Button
private lateinit var btnUpdate: Button
private lateinit var sqLiteHelper: SQLiteHelper
private lateinit var recyclerView: RecyclerView
private var adapter: StudentAdapter?=null
private var std:StudentModel?=null
val dataHolder = "DataHolder"
#RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_all_recordpage)
val textView: TextView =findViewById(R.id.DateText)
val simpleDateFormat= SimpleDateFormat("yyyy/MM/dd\n HH:mm", Locale.getDefault()).format(
Date()
)
val currentDateAndTime: String = simpleDateFormat.format(Date())
textView.text = currentDateAndTime
val button = findViewById<Button>(R.id.goBackToHome)
button.setOnClickListener{
val intent = Intent(this,MainMenu::class.java)
startActivity(intent)
}
initView()
initRecyclerView()
sqLiteHelper= SQLiteHelper(this)
//Show recycler view
val stdList = sqLiteHelper.getAllStudent()
Log.e("おっけ","${stdList.size}")
adapter?.setOnClickItem {
//購入・使用編集画面に遷移
if(it.buyamount > 0){
val intent = Intent(this,buyDetailsScreen::class.java)
intent.putExtra("date",it.email)
intent.putExtra("name", it.name)
intent.putExtra("buyAmount", it.buyamount)
startActivity(intent)
}else if (it.useamount > 0){
val intent = Intent(this,useDetailsScreen::class.java)
intent.putExtra("date",it.email)
intent.putExtra("name",it.name)
intent.putExtra("useAmount",it.useamount)
intent.putExtra("reason",it.reason)
startActivity(intent)
}else{
Toast.makeText(this,"エラーが発生しました",Toast.LENGTH_LONG).show()
}
}
adapter?.addItems(stdList)
adapter?.setOnClickDeleteItem{
deleteStudent(it.id)
}
}
private fun deleteStudent(id:Int){
val builder = AlertDialog.Builder(this)
builder.setMessage("データを削除してよろしいですか")
builder.setCancelable(true)
builder.setNegativeButton("いいえ"){dialog, _ ->
dialog.dismiss()
}
builder.setPositiveButton("はい"){dialog, _ ->
sqLiteHelper.deleteStudentById(id)
getStudents()
dialog.dismiss()
}
val alert = builder.create()
alert.show()
}
private fun updateStudent(){
val name = edName.text.toString()
val email = edEmail.text.toString()
val buyAmount = edBuyAmount.text.toString().toInt()
val useAmount = edUseAmount.text.toString().toInt()
val reason = edReason.text.toString()
//Check record not changed
if(name == std?.name && email == std?.email && buyAmount == std?.buyamount && useAmount == std?.useamount && reason == std?.reason){
Toast.makeText(this,"データが変更されてない", Toast.LENGTH_SHORT).show()
return
}
if(std == null) return
val std = StudentModel(id=std!!.id,name = name,email = email, buyamount = buyAmount, useamount = useAmount, reason = reason)
val status = sqLiteHelper.updateStudent(std)
if(status > -1){
clearEditText()
getStudents()
}else{
Toast.makeText(this,"更新失敗した", Toast.LENGTH_SHORT).show()
}
}
private fun getStudents(){
val stdList = sqLiteHelper.getAllStudent()
Log.e("おっけ","${stdList.size}")
adapter?.addItems(stdList)
}
private fun addStudent(){
val name = edName.text.toString()
val email = edEmail.text.toString()
val buyAmount = edBuyAmount.text.toString().toInt()
val useAmount = edUseAmount.text.toString().toInt()
val reason = edReason.text.toString()
if(name.isEmpty()||email.isEmpty()|| buyAmount.toString().isEmpty() ||useAmount.toString().isEmpty() || reason.toString().isEmpty()){
Toast.makeText(this,"データを入力してください", Toast.LENGTH_SHORT).show()
}else{
val std = StudentModel(name = name, email=email, buyamount=buyAmount, useamount=useAmount, reason = reason)
val status = sqLiteHelper.insertStudent(std)
//Check Insert success or not success
if(status > -2){
Toast.makeText(this,"データを追加しました。", Toast.LENGTH_SHORT).show()
clearEditText()
}else{
Toast.makeText(this,"データが保存されてないようです。", Toast.LENGTH_SHORT).show()
}
}
}
private fun clearEditText(){
edName.setText("")
edEmail.text = ""
edBuyAmount.setText("")
edUseAmount.setText("")
edReason.setText("")
edName.requestFocus()
}
private fun initRecyclerView(){
recyclerView.layoutManager=LinearLayoutManager(this)
adapter = StudentAdapter()
recyclerView.adapter=adapter
}
private fun initView(){
recyclerView=findViewById(R.id.recyclerView)
}
}
I have the code to edit/delete but first of all how do I get the popup menu to work in my recyclerview?

API is fetching all the JSON data but my app displays only one in recycler view what should i do?

I am making a simple recipe search app using recipe search API but the problem is the app fetches all the data from API but my app displays only one in recycler view then what should I do? Please help
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var recipeViewModel: RecipeViewModel
lateinit var mainBinding: ActivityMainBinding
lateinit var recipeAdapter: RecipeAdapter
lateinit var recipeItemList: ArrayList<Recipes>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainBinding.root)
recipeViewModel =
ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory
.getInstance(application)
)[RecipeViewModel::class.java]
recipeItemList = arrayListOf()
mainBinding.recyclerView.layoutManager = LinearLayoutManager(this)
recipeViewModel.recipeLiveData.observe(this, Observer { recipeItems ->
recipeItemList.add(recipeItems)
recipeAdapter = RecipeAdapter(this, recipeItemList)
mainBinding.recyclerView.adapter = recipeAdapter
Log.d("RESPONSE", recipeItems.toString())
Log.d("List size", recipeAdapter.itemCount.toString())
})
searchRecipeName()
}
private fun searchRecipeName() {
mainBinding.searchRecipeFabBtn.setOnClickListener {
val view = layoutInflater.inflate(R.layout.recipe_search_layout, null)
val searchRecipeET = view.findViewById<EditText>(R.id.searchRecipeET)
val searchRecipeBtn = view.findViewById<Button>(R.id.searchRecipeBtn)
val bottomSheetDialog = BottomSheetDialog(this)
bottomSheetDialog.apply {
this.setContentView(view)
this.show()
}
searchRecipeBtn.setOnClickListener {
val recipeName = searchRecipeET.text.toString()
searchRecipeName(recipeName, searchRecipeET, bottomSheetDialog)
}
}
}
private fun searchRecipeName(
recipeName: String,
searchRecipeET: EditText,
bottomSheetDialog: BottomSheetDialog
) {
if (recipeName.isEmpty()) {
searchRecipeET.error = "Please enter recipe name"
} else {
recipeViewModel.getRecipes(recipeName)
bottomSheetDialog.dismiss()
}
}
}
RecipeAdapter.kt
class RecipeAdapter(val context: Context, val recipesList: ArrayList<Recipes> = arrayListOf()) : RecyclerView.Adapter<RecipeAdapter.RecipeViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.recipe_items_layout, null, false)
return RecipeViewHolder(view)
}
override fun onBindViewHolder(holder: RecipeViewHolder, position: Int) {
val currentItem = recipesList[position]
holder.recipeImageView.load(currentItem.hits[3].recipe.image)
holder.recipeNameText.text = currentItem.hits[4].recipe.label
}
override fun getItemCount(): Int {
return recipesList.size
}
class RecipeViewHolder(itemView: View) :RecyclerView.ViewHolder(itemView) {
val recipeImageView: ImageView = itemView.findViewById(R.id.recipeImageView)
val recipeNameText: TextView = itemView.findViewById(R.id.recipeNameText)
}
}
RecipeViewModel.kt
class RecipeViewModel() : ViewModel() {
private val recipeRepository: RecipeRepository =
RecipeRepository(RetrofitInstance.provideApiService)
val recipeLiveData: LiveData<Recipes>
get() = recipeRepository.recipeLiveData
fun getRecipes(q:String) = viewModelScope.launch {
recipeRepository.getRecipes(q)
}
}
RecipeRepository.kt
class RecipeRepository(private val apiService: ApiService) {
private val recipeMutableLiveData: MutableLiveData<Recipes> = MutableLiveData()
val recipeLiveData: LiveData<Recipes>
get() = recipeMutableLiveData
suspend fun getRecipes(q:String){
val response = apiService.getRecipes(q)
recipeMutableLiveData.value = response.body()
}
}
APIService.kt
interface ApiService {
#GET("/api/recipes/v2?type=public&app_id=${APP_ID.appId}&app_key=${API_KEY.apiKey}")
suspend fun getRecipes(#Query("q") q:String): Response<Recipes>
}
Logs
2022-03-01 17:06:00.267 14222-14222/com.yash1307.digitalrecipebook D/RESPONSE: Recipes(hits=[Hit(recipe=Recipe(calories=308.34999999999997, dietLabels=[Low-Carb, Low-Sodium], healthLabels=[Sugar-Conscious, Low Potassium, Kidney-Friendly, Keto-Friendly, Vegetarian, Pescatarian, Paleo, Mediterranean, Dairy-Free, Gluten-Free, Wheat-Free, Peanut-Free, Tree-Nut-Free, Soy-Free, Fish-Free, Shellfish-Free, Pork-Free, Red-Meat-Free, Crustacean-Free, Celery-Free, Mustard-Free, Sesame-Free, Lupine-Free, Mollusk-Free, Alcohol-Free, No oil added, Sulfite-Free, FODMAP-Free, Kosher], image=https://www.edamam.com/web-img/20f/20f0c2553240a2c6bc639d64df3f9df4.jpg, label=Poached Eggs, totalNutrients=TotalNutrients(CA=CAX(label=Calcium, quantity=120.69999999999999, unit=mg), CHOCDF=CHOCDFX(label=Carbs, quantity=1.5499999999999998, unit=g), CHOLE=CHOLEX(label=Cholesterol, quantity=799.8, unit=mg), ENERC_KCAL=ENERCKCALX(label=Energy, quantity=308.34999999999997, unit=kcal), FAT=FATX(label=Fat, quantity=20.4465, unit=g), FE=FEX(label=Iron, quantity=3.764, unit=mg), K=KX(label=Potassium, quantity=296.8, unit=mg), MG=MGX(label=Magnesium, quantity=25.849999999999998, unit=mg), NA=NAX(label=Sodium, quantity=305.40000000000003, unit=mg), PROCNT=PROCNTX(label=Protein, quantity=27.004, unit=g)))), Hit(recipe=Recipe(calories=786.91, dietLabels=[Low-Carb], healthLabels=[Sugar-Conscious, Low Potassium, Kidney-Friendly, Vegetarian, Pescatarian, Peanut-Free, Tree-Nut-Free, Soy-Free, Fish-Free, Shellfish-Free, Pork-Free, Red-Meat-Free, Crustacean-Free, Celery-Free, Mustard-Free, Sesame-Free, Lupine-Free, Mollusk-Free, Alcohol-Free, Sulfite-Free, Kosher, Immuno-Supportive], image=https://www.edamam.com/web-img/943/943f98393348d0daf5f239e328c0bb5d.jpg, label=Moonstruck eggs, totalNutrients=TotalNutrients(CA=CAX(label=Calcium, quantity=142.34, unit=mg), CHOCDF=CHOCDFX(label=Carbs, quantity=28.896199999999997, unit=g), CHOLE=CHOLEX(label=Cholesterol, quantity=472.57000000000005, unit=mg), ENERC_KCAL=ENERCKCALX(label=Energy, quantity=786.91, unit=kcal), FAT=FATX(label=Fat, quantity=67.6459, unit=g), FE=FEX(label=Iron, quantity=3.5434, unit=mg), K=KX(label=Potassium, quantity=238.37999999999997, unit=mg), MG=MGX(label=Magnesium, quantity=37.84, unit=mg), NA=NAX(label=Sodium, quantity=424.57, unit=mg), PROCNT=PROCNTX(label=Protein, quantity=17.622700000000002, unit=g)))), Hit(recipe=Recipe(calories=451.61312499999997, dietLabels=[], healthLabels=[Sugar-Conscious, Low Potassium, Kidney-Friendly, Keto-Friendly, Vegetarian, Pescatarian, Mediterranean, Dairy-Free, Peanut-Free, Tree-Nut-Free, Soy-Free, Fish-Free, Shellfish-Free, Pork-Free, Red-Meat-Free, Crustacean-Free, Celery-Free, Mustard-Free, Sesame-Free, Lupine-Free, Mollusk-Free, Alcohol-Free, Sulfite-Free, Kosher], image=https://www.edamam.com/web-img/558/558ccc3d6e43aaf065322133ad6287b0.jpg, label=Poached Eggs, totalNutrients=TotalNutrients(CA=CAX(label=Calcium, quantity=197.9872197236699, unit=mg), CHOCDF=CHOCDFX(label=Carbs, quantity=29.56533125, unit=g), CHOLE=CHOLEX(label=Cholesterol, quantity=744.0, unit=mg), ENERC_KCAL=ENERCKCALX(label=Energy, quantity=451.61312499999997, unit=kcal), FAT=FATX(label=Fat, quantity=21.014962499999996, unit=g), FE=FEX(label=Iron, quantity=5.603875052450463, unit=mg), K=KX(label=Potassium, quantity=394.53073990789, unit=mg), MG=MGX(label=Magnesium, quantity=53.41204561348624, unit=mg), NA=NAX(label=Sodium, quantity=728.8926375, unit=mg), PROCNT=PROCNTX(label=Protein, quantity=31.436606249999997, unit=g)))), Hit(recipe=Recipe(calories=2863.0874999990874, dietLabels=[Low-Carb], healthLabels=[Sugar-Conscious, Peanut-Free, Tree-Nut-Free, Soy-Free, Fish-Free, Shellfish-Free, Crustacean-Free, Celery-Free, Mustard-Free, Sesame-Free, Lupine-Free, Mollusk-Free, Alcohol-Free, Sulfite-Free], image=https://www.edamam.com/web-img/48a/48ae883aa945c01b0b8c590d40e6fd34.jpg, label=Eggs Benedict, totalNutrients=TotalNutrients(CA=CAX(label=Calcium, quantity=584.8499999983388, unit=mg), CHOCDF=CHOCDFX(label=Carbs, quantity=89.18834999989487, unit=g), CHOLE=CHOLEX(label=Cholesterol, quantity=1377.6524999998987, unit=mg), ENERC_KCAL=EN
App image
Here is the image that displays only one item
Recipe Items Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="6dp"
app:cardElevation="6dp"
app:cardUseCompatPadding="true">
<ImageView
android:id="#+id/recipeImageView"
android:layout_width="140dp"
android:layout_height="140dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_baseline_search_24" />
<TextView
android:id="#+id/recipeNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="12dp"
android:textSize="20sp"
tools:text="Recipe Name" />
</com.google.android.material.card.MaterialCardView>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/searchRecipeFabBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="#+id/recyclerView"
app:layout_constraintHorizontal_bias="0.957"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/recyclerView"
app:layout_constraintVertical_bias="0.950"
app:srcCompat="#drawable/ic_baseline_search_24"
android:focusable="true"
android:contentDescription="#string/search_recipes" />
</androidx.constraintlayout.widget.ConstraintLayout>
Reicpes.kt (data class)
data class Recipes(
val hits: ArrayList<Hit>,
)
Hit.kt (data class)
data class Hit(
val recipe: Recipe
)
Recipe.kt (data class)
data class Recipe(
val calories: Double,
val dietLabels: List<String>,
val healthLabels: List<String>,
val image: String,
val label: String,
val totalNutrients: TotalNutrients,
)
in your Adapter you trying to get recipesList size which is contain only one item hits in it
override fun getItemCount(): Int {
return recipesList.size
}
I think you need to use recipesList.hits.size instead of recipesList.size
override fun getItemCount(): Int {
return recipesList.hits.size
}

Communication between ViewPager's host Fragment and ViewPager's Fragment item

I have a Fragment(InsiraDocumentosFragment) that has a viewpager and in that fragment I initialize an adapter(InsiraDocumentoAdapter) to initialize the viewpager.
The adapter(InsiraDocumentoAdapter) initializes generic fragments (DocumentoFragment) that I update dynamically, I can now update the image that is shown inside it, but I need to get the click on that image to either change it or to remove it, but this needs to be done in the Fragment that contains the viewpager, because is in this fragment(InsiraDocumentosFragment) that I have the viewmodel that communicates with the database.
How can I watch from InsiraDocumentosFragment the click on the imageview of DocumentFragment ?
Here are my code samples.
class InsiraDocumentosFragment : Fragment() {
private lateinit var _view: View
private lateinit var _imgBack: ImageView
private lateinit var _viewpager: ViewPager
private lateinit var _imgCamera: ImageView
private lateinit var _footerTitle: TextView
private lateinit var _titles: List<String>
private lateinit var _files: MutableList<File?>
private lateinit var _viewModel: DocumentoViewModel
private lateinit var _viewModelProposta: PropostaViewModel
private lateinit var _viewModelArquivo: ArquivoViewModel
private lateinit var _adapter: InsiraDocumentoAdapter
private lateinit var _proposta: PropostaEntity
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_insira_documento, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_view = view
_imgBack = _view.findViewById(R.id.imgBack)
_viewpager = _view.findViewById(R.id.viewpager)
_imgCamera = _view.findViewById(R.id.cameraDocumento)
_footerTitle = _view.findViewById(R.id.footerTitle)
_files = mutableListOf(null, null, null)
_titles = listOf(getString(R.string.identidade), getString(R.string.comprovante_renda), getString(R.string.foto))
_adapter = InsiraDocumentoAdapter(_titles, _files, childFragmentManager)
_viewpager.adapter = _adapter
_viewModel = ViewModelProvider(
this,
DocumentoViewModel.DocumentoViewModelFactory(DocumentoRepositorio(AppDatabase.getDatabase(_view.context).documentoDao()))
).get(DocumentoViewModel::class.java)
_viewModelProposta = ViewModelProvider(
this,
PropostaViewModel.PropostaViewModelFactory(PropostaRepositorio(AppDatabase.getDatabase(_view.context).propostaDao()))
).get(PropostaViewModel::class.java)
_viewModelArquivo = ViewModelProvider(
this,
ArquivoViewModel.ArquivoViewModelFactory(ArquivoRepositorio(AppDatabase.getDatabase(_view.context).arquivoDao()))
).get(ArquivoViewModel::class.java)
addViewPagerListener()
onClickImgBack()
onClickImgCamera()
onClickFooterTitle()
val propostaStr = arguments?.getString(PROPOSTA)
if (!propostaStr.isNullOrBlank()) {
_proposta = jsonToObjProposta(propostaStr)
}
}
private fun addViewPagerListener() {
_viewpager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
if (position == _viewpager.adapter!!.count - 1) {
_footerTitle.text = getString(R.string.concluir)
} else {
_footerTitle.text = getString(R.string.proximo)
}
updateViewPagerLayout(position)
}
})
}
private fun updateViewPagerLayout(currentPage: Int) {
when (currentPage) {
0 -> {
habilitaIndicadorPagina(_view.findViewById(R.id.primeiraPagina), _view.findViewById(R.id.imgPrimeiraPagina), R.drawable.primeira_pagina_selecionada)
desabilitaIndicadorPagina(_view.findViewById(R.id.segundaPagina), _view.findViewById(R.id.imgSegundaPagina), R.drawable.segunda_pagina_nao_selecionada)
desabilitaIndicadorPagina(_view.findViewById(R.id.terceiraPagina), _view.findViewById(R.id.imgTerceiraPagina), R.drawable.terceira_pagina_nao_selecionada)
}
1 -> {
desabilitaIndicadorPagina(_view.findViewById(R.id.primeiraPagina), _view.findViewById(R.id.imgPrimeiraPagina), R.drawable.primeira_pagina_nao_selecionada)
habilitaIndicadorPagina(_view.findViewById(R.id.segundaPagina), _view.findViewById(R.id.imgSegundaPagina), R.drawable.segunda_pagina_selecionada)
desabilitaIndicadorPagina(_view.findViewById(R.id.terceiraPagina), _view.findViewById(R.id.imgTerceiraPagina), R.drawable.terceira_pagina_nao_selecionada)
}
2 -> {
desabilitaIndicadorPagina(_view.findViewById(R.id.primeiraPagina), _view.findViewById(R.id.imgPrimeiraPagina), R.drawable.primeira_pagina_nao_selecionada)
desabilitaIndicadorPagina(_view.findViewById(R.id.segundaPagina), _view.findViewById(R.id.imgSegundaPagina), R.drawable.segunda_pagina_nao_selecionada)
habilitaIndicadorPagina(_view.findViewById(R.id.terceiraPagina), _view.findViewById(R.id.imgTerceiraPagina), R.drawable.terceira_pagina_selecionada)
}
}
}
private fun desabilitaIndicadorPagina(layout: ConstraintLayout, image: ImageView, imageDrawable: Int) {
layout.setBackgroundResource(R.drawable.not_selected_indicator)
image.setBackgroundResource(imageDrawable)
}
private fun habilitaIndicadorPagina(layout: ConstraintLayout, image: ImageView, imageDrawable: Int, ) {
layout.setBackgroundResource(R.drawable.indicador_selecionado)
image.setBackgroundResource(imageDrawable)
}
private fun onClickFooterTitle() {
_footerTitle.setOnClickListener {
if (_viewpager.currentItem == _viewpager.adapter!!.count - 1) {
var success = true
for (i in 0..2) {
if (_files[i] == null || _files[i]?.path.isNullOrEmpty()) {
Toast.makeText(_view.context, R.string.favor_preencher_todas_as_fotos, Toast.LENGTH_LONG).show()
_viewpager.currentItem = i
success = false
break
}
}
if (success) {
_viewModelProposta.addProposta(_proposta.numeroProposta, _proposta.valorPropasta, _proposta.clienteId).observe(viewLifecycleOwner, { idProposta ->
_proposta.id = idProposta
_viewModel.addDocumento("Nome do Documento", _proposta.id).observe(viewLifecycleOwner, { idDocumento ->
val arquivos = mutableListOf<ArquivoEntity>()
for (i in 0..2) {
arquivos.add(ArquivoEntity(0, _files[i]!!.path, _titles[i], idDocumento))
}
_viewModelArquivo.addArquivos(arquivos).observe(viewLifecycleOwner, {
_view.findNavController().popBackStack(R.id.clienteFragment, false)
})
})
})
}
} else {
_viewpager.currentItem = _viewpager.currentItem + 1
}
}
}
private fun onClickImgBack() {
_imgBack.setOnClickListener {
_view.findNavController().navigateUp()
}
}
private fun onClickImgCamera() {
_imgCamera.setOnClickListener {
val intent = Intent(_view.context, ScannerActivity::class.java)
startActivityForResult(intent, REQUEST_CODE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val mediaList = ScannerActivity.getOutputDirectory(_view.context).listFiles()?.toMutableList() ?: mutableListOf()
if (mediaList.size > 0) {
val documentoFile = mediaList[mediaList.size - 1]
_files.removeAt(_viewpager.currentItem)
_files.add(_viewpager.currentItem, documentoFile)
_adapter.notifyDataSetChanged()
}
}
}
private fun jsonToObjProposta(json: String): PropostaEntity {
val gson = Gson()
val arrayTutorialType = object : TypeToken<PropostaEntity>() {}.type
return gson.fromJson(json, arrayTutorialType)
}
override fun onResume() {
super.onResume()
_view = requireView()
}
companion object {
const val REQUEST_CODE = 1
const val IMAGE = "IMAGE"
const val ID_PROPOSTA = "ID_PROPOSTA"
const val PROPOSTA = "PROPOSTA"
}
}
class InsiraDocumentoAdapter(private val titles: List<String>, private var files: List<File?>, manager: FragmentManager): FragmentStatePagerAdapter(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getCount() = 3
override fun getItem(position: Int): Fragment {
return DocumentoFragment.newInstance(titles[position], files[position])
}
override fun getItemPosition(`object`: Any): Int {
return POSITION_NONE
}
}
class DocumentoFragment : Fragment() {
private lateinit var _view: View
private lateinit var _documento: ImageView
private lateinit var _documentoShape: ImageView
private lateinit var _txtTitle: TextView
private var _file: File? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_documento, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_view = view
}
private fun setUpView() {
_documento = _view.findViewById(R.id.documento)
_documentoShape = _view.findViewById(R.id.documentoShape)
_txtTitle = _view.findViewById(R.id.txtTitle)
_txtTitle.text = arguments?.getString(TITLE)
if (!arguments?.getString(FILE).isNullOrEmpty()) {
_file = File(arguments?.getString(FILE))
}
onImgClick()
insereImagem()
}
private fun onImgClick() {
_documento.setOnClickListener {
if (_documentoShape.visibility == View.GONE && _file != null) {
val intent = Intent(_view.context, FullScreenActivity::class.java)
intent.putExtra(InsiraDocumentosFragment.IMAGE, _file?.path)
intent.putExtra(TITLE, _txtTitle.text)
startActivity(intent)
}
}
}
private fun insereImagem() {
if (_file != null) {
Picasso.get().load(_file!!).into(_view.findViewById<ImageView>(R.id.documento))
_view.findViewById<ImageView>(R.id.documentoShape)?.visibility = View.GONE
} else {
_view.findViewById<ImageView>(R.id.documentoShape)?.visibility = View.VISIBLE
}
}
override fun onResume() {
super.onResume()
setUpView()
}
companion object {
fun newInstance(title: String, file: File?): DocumentoFragment {
val fragmentFirst = DocumentoFragment()
val args = bundleOf(
TITLE to title,
FILE to file?.path
)
fragmentFirst.arguments = args
return fragmentFirst
}
const val TITLE = "TITLE"
const val FILE = "FILE"
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".documento.view.DocumentoFragment">
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="#dimen/dimen_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Identidade"
android:textColor="#015669"
android:textSize="#dimen/dimen_20sp"
/>
<ImageView
android:id="#+id/documento"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#ffffff"
android:src="#drawable/rectangle_white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/txtTitle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:scaleType="fitXY"
android:layout_marginTop="#dimen/dimen_20dp"
android:contentDescription="#string/foto_documento"/>
<ImageView
android:id="#+id/documentoShape"
android:layout_width="88dp"
android:layout_height="101dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:src="#drawable/document_shape"
android:contentDescription="#string/foto_documento"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".documento.view.InsiraDocumentosFragment"
android:background="#f0f0f0">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="#dimen/dimen_56dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/rectangle_blue_toolbar">
<ImageView
android:id="#+id/imgBack"
android:layout_width="#dimen/dimen_12dp"
android:layout_height="#dimen/dimen_20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="#dimen/dimen_20dp"
android:layout_marginTop="18dp"
android:src="#drawable/tint_color"
android:contentDescription="#string/voltar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="#string/insira_os_documentos"
android:textColor="#ffffff"
android:textSize="#dimen/dimen_20sp"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/pagerIndicator"
android:layout_width="wrap_content"
android:layout_height="#dimen/dimen_30dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/toolbar"
android:layout_marginTop="#dimen/dimen_20dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/primeiraPagina"
android:layout_width="#dimen/dimen_30dp"
android:layout_height="#dimen/dimen_30dp"
android:background="#drawable/indicador_selecionado"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/segundaPagina"
android:layout_marginHorizontal="#dimen/dimen_10dp"
>
<ImageView
android:id="#+id/imgPrimeiraPagina"
android:layout_width="#dimen/dimen_9dp"
android:layout_height="#dimen/dimen_18dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:background="#drawable/primeira_pagina_selecionada"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/segundaPagina"
android:layout_width="#dimen/dimen_30dp"
android:layout_height="#dimen/dimen_30dp"
android:background="#drawable/not_selected_indicator"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/primeiraPagina"
android:layout_marginHorizontal="#dimen/dimen_10dp"
>
<ImageView
android:id="#+id/imgSegundaPagina"
android:layout_width="#dimen/dimen_9dp"
android:layout_height="#dimen/dimen_18dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:background="#drawable/segunda_pagina_nao_selecionada"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/terceiraPagina"
android:layout_width="#dimen/dimen_30dp"
android:layout_height="#dimen/dimen_30dp"
android:background="#drawable/not_selected_indicator"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/segundaPagina"
android:layout_marginHorizontal="#dimen/dimen_10dp"
>
<ImageView
android:id="#+id/imgTerceiraPagina"
android:layout_width="#dimen/dimen_9dp"
android:layout_height="#dimen/dimen_18dp"
android:layout_gravity="center"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:background="#drawable/terceira_pagina"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="#dimen/dimen_280dp"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/pagerIndicator"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="#id/footer"
android:layout_marginHorizontal="#dimen/dimen_40dp"
android:layout_marginTop="#dimen/dimen_20dp"
android:layout_marginBottom="#dimen/dimen_20dp"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="#dimen/dimen_69dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:background="#drawable/footer">
<ImageView
android:id="#+id/imgDocumento"
android:layout_width="#dimen/dimen_26dp"
android:layout_height="#dimen/dimen_30dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginStart="#dimen/dimen_20dp"
android:layout_marginVertical="#dimen/dimen_20dp"
android:src="#drawable/combined_shape"
android:backgroundTint="#0179b0"
android:contentDescription="#string/formato_documento"
/>
<TextView
android:id="#+id/footerTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="#id/imgDocumento"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toStartOf="#+id/cameraDocumento"
app:layout_constraintBottom_toBottomOf="parent"
android:textSize="#dimen/dimen_20sp"
android:textColor="#0179b0"
android:gravity="center"
android:text="#string/proximo"/>
<ImageView
android:id="#+id/cameraDocumento"
android:layout_width="#dimen/dimen_33dp"
android:layout_height="#dimen/dimen_30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="#dimen/dimen_20dp"
android:layout_marginVertical="#dimen/dimen_20dp"
android:src="#drawable/camera_shape"
android:backgroundTint="#0179b0"
android:contentDescription="#string/capturar_foto"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I need to get the click on that image to either change it or to remove it, but this needs to be done in the Fragment that contains the viewpager, because is in this fragment(InsiraDocumentosFragment) that I have the viewmodel that communicates with the database.
You have a couple of options to do that:
First one:
Make the ViewModel shared between both fragments (InsiraDocumentosFragment & DocumentoFragment) by instantiating it in both fragments with the activity as the owner using requireActivity() that hosts both fragments:
val viewModel =
ViewModelProvider(requireActivity()).get(MyViewModel::class.java)
And then no need to access the parent fragment for changing the image; because now you've an instance of the ViewModel in the DocumentoFragment.
Second one:
Access the InsiraDocumentosFragment from the DocumentoFragment using requireParentFragment(), but first create a method in parent that you want to call from the page fragment to do your needed job.
Assuming the method that you created in InsiraDocumentosFragment is someMethodInParent()
In DocumentoFragment:
val parentFragment = requireParentFragment() as InsiraDocumentosFragment
parentFragment.someMethodInParent()

how to binding correctly recyclerview items in kotlin?

I am developing a news app and I am following MVVM with data binding in recycler view I am trying to bind items but I am just stuck below my recyclerview items xml file
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="article"
type="yodgorbek.komilov.musobaqayangiliklari.model.Article">
</variable>
</data>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp">
<ImageView
android:text="#{article.urlToImage}"
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="85dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:contentDescription="bbc"
tools:background="#color/colorPrimary" />
<TextView
android:id="#+id/articleTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_toEndOf="#id/imageView"
android:layout_toRightOf="#id/imageView"
android:ellipsize="end"
android:lines="3"
android:maxLines="3"
android:text="#{article.title}" />
<ImageView
android:id="#+id/imageCategory"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_below="#id/articleTitle"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_toEndOf="#id/imageView"
android:layout_toRightOf="#id/imageView"
android:src="#drawable/ic_espn"
tools:background="#color/colorPrimary" />
<TextView
android:id="#+id/articleSourceName"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:layout_below="#id/articleTitle"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_toEndOf="#id/imageCategory"
android:layout_toRightOf="#id/imageCategory"
android:gravity="center|start"
android:text="#{article.source.name}" />
<TextView
android:id="#+id/articleTime"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:layout_below="#id/articleTitle"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_toEndOf="#id/articleSourceName"
android:layout_toRightOf="#id/articleSourceName"
android:gravity="center|start"
android:text="#{article.publishedAt}"
android:textColor="#android:color/darker_gray"
tools:ignore="NotSibling" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</layout>
below TopHeadlinesAdapter.kt where I am trying to implement data binding logic
#Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class TopHeadlinesAdapter(val context: Context, private val article: List<Article>) :
RecyclerView.Adapter<TopHeadlinesAdapter.MyViewHolder>() {
private var articleList: List<Article> by Delegates.observable(emptyList()) { _, _, _ ->
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater =
LayoutInflater.from(parent.context)//.inflate(R.layout.news_list, parent, false)
// val binding = Article.inflate(inflater)
return MyViewHolder(article, parent)
}
override fun getItemCount(): Int {
return articleList.size
}
#SuppressLint("NewApi")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) =
holder.bind(articleList[position])
//holder.articleTitle.text = articleList.get(position).title
//holder.articleSourceName.text = articleList.get(position).source.name
//Picasso.get().load(articleList.get(position).urlToImage).into(holder.image)
// val input = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
// val output = SimpleDateFormat("dd/MM/yyyy")
// var d = Date()
// try {
// d = input.parse(articleList[5].publishedAt)
// } catch (e: ParseException) {
// try {
// val fallback = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
// fallback.timeZone = TimeZone.getTimeZone("UTC")
// d = fallback.parse(articleList[5].publishedAt)
// } catch (e2: ParseException) {
// // TODO handle error
// val formatted = output.format(d)
// val timelinePoint = LocalDateTime.parse(formatted)
// val now = LocalDateTime.now()
//
// var elapsedTime = Duration.between(timelinePoint, now)
//
// println(timelinePoint)
// println(now)
// elapsedTime.toMinutes()
//
// holder.articleTime.text = "${elapsedTime.toMinutes()}"
//
//
fun updateData(newList: List<Article>) {
articleList = newList
Log.e("articleListSize", articleList?.size.toString())
}
inner class MyViewHolder(private val binding: Article) : RecyclerView.ViewHolder(binding.root) {
fun bind(article: Article) {
binding.article = article
// val image: ImageView = itemView!!.findViewById(R.id.imageView)
// val articleTitle: TextView = itemView!!.findViewById(R.id.articleTitle)
// val articleSourceName: TextView = itemView!!.findViewById(R.id.articleSourceName)
// val imageCategory: ImageView = itemView!!.findViewById(R.id.imageCategory)
// val articleTime: TextView = itemView!!.findViewById(R.id.articleTime)
}
}
}
below my Article.kt data class
data class Article(
val author: String,
val content: String,
val description: String,
val publishedAt: String,
val source: Source,
val title: String,
val url: String,
val urlToImage: String
)
below fragment_top_headlines.xml where I am hosting recyclerview
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/pb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
below TopHeadlinesFragment.kt
class TopHeadlinesFragment : Fragment() {
private val viewModel by viewModel<MainViewModel>()
private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
// private val newsRepository: NewsRepository by inject()
private lateinit var article:List<Article>
//3
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(
R.layout.fragment_top_headlines
, container, false
)
val recyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
val pb = view.findViewById(R.id.pb) as ProgressBar
topHeadlinesAdapter = TopHeadlinesAdapter(recyclerView.context, article)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = topHeadlinesAdapter
initViewModel()
return view
}
private fun initViewModel() {
viewModel?.sportList?.observe(this, Observer { newList ->
topHeadlinesAdapter.updateData(newList)
})
viewModel?.showLoading?.observe(this, Observer { showLoading ->
pb.visibility = if (showLoading) View.VISIBLE else View.GONE
})
viewModel?.showError?.observe(this, Observer { showError ->
(showError)
})
viewModel?.loadNews()
}
}
I want to know what I have to do in order to bind correctly recyclerview items and show correctly in my app?
try this in
class yourAdapterName(val context: Context, var listData:
MutableList<Article>) :
RecyclerView.Adapter<LanguageAdapter.ViewHolder>() {
lateinit var bindind: YourBinding
fun onRefresh(listData: MutableList<Article>) {
this.listData = listData
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
ViewHolder {
bindind = YourBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(bindind)
}
override fun getItemCount(): Int {
return listData.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.setData(listData[position])
}
inner class ViewHolder(private val binding: LangugaeItemBinding) : RecyclerView.ViewHolder(binding.getRoot()) {
fun setData(model: Article) {
with(binding) {
artical = model
executePendingBindings()
}
}
}
}
and call these into onViewCreated in fragment
val recyclerView = view.findViewById(R.id.recyclerView) as
RecyclerView
val pb = view.findViewById(R.id.pb) as ProgressBar
topHeadlinesAdapter = TopHeadlinesAdapter(recyclerView.context,
article)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = topHeadlinesAdapter
initViewModel()

why retrofit returning empty data?

I am developing a new android app but My app getting showing empty data in recycler view in MainActivity and I have put a breakpoint there are also showing null but I am already initializing data I want to know where I am making mistake what I am missing?
below my RestClient.kt
class RestClient {
internal val httpLoggingInterceptor: HttpLoggingInterceptor
get() {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return httpLoggingInterceptor
}
internal fun getOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build()
}
companion object {
private val ROOT_URL = "http://www.mocky.io"
/**
* Get Retrofit Instance
*/
private val retrofitInstance: Retrofit
get() = Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
/**
* Get API Service
*
* #return API Service
*/
val apiService: RestInterface
get() = retrofitInstance.create(RestInterface::class.java)
}
}
below my Post.kt data class
data class Post(
#SerializedName("description")
val description: String,
#SerializedName("id")
val id: Int,
#SerializedName("image")
val image: String,
#SerializedName("published_at")
val publishedAt: String,
#SerializedName("title")
val title: String,
#SerializedName("user_id")
val userId: Int
)
below RestList.kt
data class RestList(
#SerializedName("posts")
val posts: List<Post>
)
below my interface
interface RestInterface {
#get:GET("/v2/59f2e79c2f0000ae29542931")
val getPosts: Call<RestList>
}
below Adapter
class RestAdapter(val post: List<Post>?,val restList: RestList?) : RecyclerView.Adapter<RestAdapter.PostHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {
val itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list, null)
return PostHolder(itemView)
}
override fun getItemCount(): Int {
return post?.size!!
}
override fun onBindViewHolder(holder: PostHolder, position: Int) {
val posts = post?.get(position)
Picasso
.get() // give it the context
.load(posts?.image) // load the image
.into(holder.postImage)
holder.userId.text = posts?.userId.toString()
holder.postTitle.text = posts?.title
holder.postTime.text = posts?.publishedAt
holder.postDescription.text = posts?.description
}
class PostHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val postImage: ImageView
val userId: TextView
val postTitle: TextView
val postTime: TextView
val postDescription: TextView
init {
postImage = itemView.findViewById(R.id.postImage)
userId = itemView.findViewById(R.id.userId)
postTitle = itemView.findViewById(R.id.postTitle)
postTime = itemView.findViewById(R.id.postTime)
postDescription = itemView.findViewById(R.id.postDescription)
}
}
}
I am calling retrofit in followingly in mainactivity.kt
class MainActivity : AppCompatActivity() {
companion object{
const val TAG = "internet"
}
private var recyclerView: RecyclerView? = null
private var restAdapter: RestAdapter? = null
private var restInterface: RestInterface? = null
private var postList: List<Post>? = null
private var restList: RestList? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recycler_view)
restInterface = RestClient.apiService
val call = restInterface?.getPosts
call?.enqueue(object : Callback<RestList> {
override fun onResponse(call: Call<RestList>, response: Response<RestList>) {
if (response.body() != null) {
restList = response.body()
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView?.layoutManager = layoutManager
// initialize postList with posts
postList = restList?.posts
restAdapter = RestAdapter(postList, restList)
//this should be come later
recyclerView?.adapter = restAdapter
}
}
override fun onFailure(call: Call<RestList>, t: Throwable) {
Log.e(TAG, "There is no internet connection")
}
})
}
}
below my activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
below post_list.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.55" />
<ImageView
android:id="#+id/postImage"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="16:9"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toEndOf="#id/guideline"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/userId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="10dp"
android:text="Placeholder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/postTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Secondary"
app:layout_constraintEnd_toStartOf="#id/postImage"
app:layout_constraintStart_toStartOf="#id/userId"
app:layout_constraintTop_toBottomOf="#id/userId" />
<TextView
android:id="#+id/postTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
android:text="Tertiary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#id/userId"
app:layout_constraintTop_toBottomOf="#id/postTitle" />
<TextView
android:id="#+id/postDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
android:text="Tertiary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#id/userId"
app:layout_constraintTop_toBottomOf="#id/postTime" />
</androidx.constraintlayout.widget.ConstraintLayout>
There are multiple problems in your implementation. Check below:
Problem - 1: You didn't initialize you restInterface
restInterface = RestClient.apiService
val call = restInterface?.getPosts
Problem - 2: You didn't initialize your postList after getting from API
postList = restList?.posts
Problem - 3: Initialize your RecyclerView with null adapter as you assign adapter before initialize it
if (response.body() != null) {
restList = response.body()
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView?.layoutManager = layoutManager
// initialize postList with posts
postList = restList?.posts
restAdapter = RestAdapter(postList, restList)
//this should be come later
recyclerView?.adapter = restAdapter
}
Problem - 4: Add usesCleartextTraffic in your AndroidManifest.xml to support http request
<application
android:usesCleartextTraffic="true"
... >
I think you should define adapter before set adapter to recyclerview, swap the lines like this.
restAdapter = RestAdapter(postList, restList)
recyclerView?.adapter = restAdapter

Categories

Resources