Errors in connection of CameraFragment.kt with xml - kotlin

I need help please, i'm getting errors in fragment.kt in process of getting a camera set up
**
//fragmentcamera.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=".MainActivity">
<androidx.camera.view.PreviewView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/preview"/>
<Button
android:id="#+id/btnTakePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Take photo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#id/btnDisplayGallery"
app:layout_constraintBottom_toBottomOf="parent"/>
<Button
android:id="#+id/btnDisplayGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_marginBottom="300dp"
android:text="Display gallery"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/btnTakePhoto" />
</androidx.constraintlayout.widget.ConstraintLayout>**
The following are images for camerafragment.kt
s
the errors that i am getting

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class cameraFragment : Fragment() {
// TODO: Rename and change types of parameters
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//ListenableFuture interface listens for async operations external to
// main thread
// requires type of activity being observed - ProcessCameraProvider
private lateinit var cameraProviderFuture:
ListenableFuture<ProcessCameraProvider>
//used to decide whether to use front or back camera
private lateinit var cameraSelector: CameraSelector
//use case for capturing images
private var imageCapture: ImageCapture? = null
//interface that extends Executor to provide thread for capturing an image
private lateinit var imgCaptureExecutor: ExecutorService
//static variables
companion object {
//used for messages output in debugger
val TAG = "cameraFragment"
//used to check request code
private var REQUEST_CODE = 101
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for requireActivity() fragment
val view: View = inflater.inflate(
R.layout.xml_camera,
container,
false
)
//get instance of ProcessCameraProvider
cameraProviderFuture = ProcessCameraProvider.getInstance(requireActivity())
//set default to back camera
cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
//instantiate imgCaptureExecutor
imgCaptureExecutor = Executors.newSingleThreadExecutor()
//check for permissions (similar to other sensors)
if (ActivityCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
)
//request permissions
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(
//array containing required permissions
Manifest.permission.CAMERA
),
REQUEST_CODE
)
else {
//if permission already granted, start camera
startCamera()
}
//set up event listener for btnCapture click
val btnTakePhoto: Button = view.findViewById(R.id.btnTakePhoto)
btnTakePhoto.setOnClickListener {
takePhoto()
} //set up event listener for btnGallery click
val btnDisplayGallery: Button = view.findViewById(R.id.btnDisplayGallery)
btnDisplayGallery.setOnClickListener {
displayGallery()
}
return view
}
//invoked when permissions change
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//check that request code matches and permission granted
if (requestCode == REQUEST_CODE &&
grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
//if permission now granted, start camera
startCamera()
}
}
//listen for data from camera
private fun startCamera() {
cameraProviderFuture.addListener(
{
//create ProcessCameraProvider instance
val cameraProvider = cameraProviderFuture.get()
//connect preview use case to the preview in the xml file
val preview: PreviewView = requireView().findViewById(R.id.preview)
val previewCase = Preview.Builder().build().also {
it.setSurfaceProvider(preview.surfaceProvider)
}
//instantiate capture use case
imageCapture = ImageCapture.Builder().build()
try {
//clear all bindings to previous use cases first
cameraProvider.unbindAll()
//bind lifecycle of camera to lifecycle of application
cameraProvider.bindToLifecycle(
requireActivity(),
cameraSelector, previewCase
)
cameraProvider.bindToLifecycle(
requireActivity(), cameraSelector,
imageCapture
)
} catch (e: Exception) {
Log.d(TAG, "Use case binding failed")
}
},
//run asynchronous operation being listened to by cameraProviderFuture
ContextCompat.getMainExecutor(requireActivity())
)
}
//take photo
private fun takePhoto() {
imageCapture?.let {
//create file with fileName using timestamped in milliseconds
val file = File(
requireActivity().externalMediaDirs[0],
"snap_${System.currentTimeMillis()}"
)
//save image in above file
val outputFileOptions =
ImageCapture.OutputFileOptions.Builder(file).build()
//call takePicture method with where to find image
it.takePicture(
outputFileOptions,
imgCaptureExecutor,
//set up callbacks for when picture is taken
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(
outputFileResults:
ImageCapture.OutputFileResults
) {
Log.i(TAG, "Image saved in ${file.toUri()}")
}
override fun onError(exception: ImageCaptureException) {
Toast.makeText(
requireActivity(),
"Error taking photo",
Toast.LENGTH_LONG
).show()
Log.i(TAG, "Error taking photo: $exception")
}
}
)
}
animateFlash()
}
//flash to provide feedback that photo taken
private fun animateFlash() {
val preview: PreviewView = requireView().findViewById(R.id.preview)
preview.postDelayed({
preview.foreground = ColorDrawable(Color.argb(125, 255, 255, 255))
preview.postDelayed({
preview.foreground = null
}, 30)
}, 60)
}
//display gallery
private fun displayGallery() {
val intent = Intent(requireActivity(), GalleryActivity::class.java)
startActivity(intent)
}
}

Replace all "this,getApplicationContext" with getActivity(). In Java
Replace all "this,getApplicationContext" with activity. In Kotlin.
Two likely definitions:
getActivity() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).
getActivity() is user-defined.

Related

Kotlin :Can't get the price of the item of RecyclerView on Fragment

I am attempting to make a recyclerView on Fragment ,
The idea is to get the price of the Item ,when the item been selected ,
and multiply by the select amount from the popup menu also.
Like below :
The recyclerView model item : item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="120dp"
android:gravity="center"
android:id="#+id/cardView"
android:layout_margin="10dp"
android:background="#40E0D0"
android:layout_height="200dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price:"
android:textColor="#color/black"
android:textSize="18sp"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="100"
android:textColor="#color/black"
android:textSize="18sp"/>
</LinearLayout>
The model of the item : Product.kt :
package com.gearsrun.popmenuapplication
data class Product(var price : String)
private selectFuntion(itemPrice:Int){
}
ProductAdapter.kt
package com.gearsrun.popmenuapplication
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_layout.view.*
class ProductAdapter(private val productList:List<Product>,private val itemClick:(Int) -> Unit):RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {
private var selectedItemPosition :Int = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout,parent,false)
return ProductViewHolder(itemView,itemClick)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val currentItem = productList[position]
holder.price.text = currentItem.price.toString()
holder.itemView.setOnClickListener {
selectedItemPosition = position
notifyDataSetChanged()
}
if(selectedItemPosition == position){
holder.itemView.cardView.setBackgroundColor(Color.parseColor("#FAFAD2"))
}else{
holder.itemView.cardView.setBackgroundColor(Color.parseColor("#FFFFFF"))
}
}
override fun getItemCount() = productList.size
class ProductViewHolder(itemView: View, itemClick: (Int) -> Unit) :
RecyclerView.ViewHolder(itemView) {
val price : TextView = itemView.price
init {
itemView.setOnClickListener {
itemClick(price.text.toString().toInt()) //sortOf if you need String, change that on String in every declaration
}
}
}
}
Fragment.kt
package com.gearsrun.popmenuapplication.fragment
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import androidx.recyclerview.widget.LinearLayoutManager
import com.gearsrun.popmenuapplication.Product
import com.gearsrun.popmenuapplication.ProductAdapter
import com.gearsrun.popmenuapplication.R
import kotlinx.android.synthetic.main.fragment_home.*
class HomeFragment : Fragment(R.layout.fragment_home) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//init popup menu
val popupMenu = PopupMenu(
context,
selectedTv
)
//add menu items to popup menu
popupMenu.menu.add(Menu.NONE,0,0,"1")
popupMenu.menu.add(Menu.NONE,1,1,"2")
popupMenu.menu.add(Menu.NONE,2,2,"3")
popupMenu.menu.add(Menu.NONE,3,3,"4")
popupMenu.menu.add(Menu.NONE,4,4,"5")
//handle menu clicks
popupMenu.setOnMenuItemClickListener {menuItem ->
//get id of the item clicked
val id = menuItem.itemId
if(id==0){
selectedTv.text = "1"
}else if(id==1){
selectedTv.text = "2"
}else if(id==2){
selectedTv.text = "3"
}else if(id==3){
selectedTv.text = "4"
}else if(id==4){
selectedTv.text = "5"
}
true
}
//handle button click,show menu
selectedTv.setOnClickListener {
popupMenu.show()
}
//display recyclerview
val productList = generateProductList()
fun selectFuntion(itemPrice: Int){
Log.e("haha","You have click${itemPrice}")
}
var adapter = ProductAdapter(productList,::selectFuntion)
giftRecycleView.adapter = adapter
giftRecycleView.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)
}
private fun generateProductList():List<Product> {
val list = ArrayList<Product>()
list.add(Product(1))
list.add(Product(2))
list.add(Product(3))
return list
}
}
Can anyone help me modify my code ?
I will need that the item's value can be catch once click ,and multiply by the select amount ,in order to get the total price .
Thank you so much in advance !!
ProductAdapter.kt
add this:
class ProductAdapter(
private val productList:List<Product>,
private val itemClick: (Int) -> Unit
): RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {
delete this:
interface onItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener) {
mlistener = listener
}
replace this:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout,parent,false)
return ProductViewHolder(itemView,itemClick)
}
replace this:
class ProductViewHolder(itemView: View, itemClick: (Int) -> Unit) :
RecyclerView.ViewHolder(itemView) {
val price : TextView = itemView.price
init {
itemView.setOnClickListener {
itemclick(price.text.toInt()) //sortOf if you need String, change that on String in every declaration
}
}
}
replace in fragment:
var adapter = ProductAdapter(productList, ::yourFunction)
giftRecycleView.adapter = adapter
add in fragment or ViewModel:
private yourFunction(itemPrice: Int) {
// do something with price
}
if you need to edit that price just make return type:
(Int) -> Int sort of :D
and in adapter
price.text = itemclick(price.text.toInt()).toString()

Kotlin : Recyclerview on Fragment ,how to make the default total price is the first item multiply 1

I got stuck in the situation ..
The idea is ,make the display total price with the first item selected multiply the first value of popup menu which is 1 ,I was trying to make the first item as the initial price ,but the total price became the first item price * selected value of popup menu ....
I have no idea what happend ..
Could you please help me check my code ,thank you so much in advance :
Product.kt
package com.gearsrun.recyclerviewfragmentapplication
data class Product(var price : String)
ProductAdapter.kt
package com.gearsrun.recyclerviewfragmentapplication
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_layout.view.*
class ProductAdapter(private val productList:List<Product>): RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {
private var selectedItemPosition :Int = 0
private var mlistener : onItemClickListener ?=null
fun interface onItemClickListener{
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener){
mlistener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout,parent,false)
return ProductViewHolder(itemView,mlistener)
}
override fun onBindViewHolder(holder: ProductAdapter.ProductViewHolder, position: Int) {
val currentItem = productList[position]
holder.price.text = currentItem.price
holder.itemView.setOnClickListener {
selectedItemPosition = position
notifyDataSetChanged()
}
if(selectedItemPosition == position){
holder.itemView.cardView.setBackgroundColor(Color.parseColor("#FAFAD2"))
}else{
holder.itemView.cardView.setBackgroundColor(Color.parseColor("#FFFFFF"))
}
}
override fun getItemCount() = productList.size
class ProductViewHolder(itemView: View,listener: onItemClickListener):RecyclerView.ViewHolder(itemView) {
val price : TextView = itemView.price
init {
itemView.setOnClickListener {
listener?.onItemClick(absoluteAdapterPosition)
}
}
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".fragment.HomeFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<!--Recycler View-->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/giftRecycleView"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="30dp"
/>
<!--Selected option will display here-->
<LinearLayout
android:layout_width="match_parent"
android:gravity="center"
android:padding="16dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select amount : "
android:textColor="#color/black"
android:textSize="18sp"/>
<TextView
android:id="#+id/selectedTv"
android:layout_width="100dp"
android:layout_height="60dp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginLeft="10dp"
android:background="#color/black"
android:textColor="#color/white"
android:textSize="20sp"
android:text="1" />
</LinearLayout>
<!--Total price-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total : "
android:textColor="#color/black"
android:textSize="18sp"/>
<TextView
android:id="#+id/price_t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="18sp"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
HomeFragment.kt
package com.gearsrun.recyclerviewfragmentapplication.fragment
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.gearsrun.recyclerviewfragmentapplication.Product
import com.gearsrun.recyclerviewfragmentapplication.ProductAdapter
import com.gearsrun.recyclerviewfragmentapplication.R
import kotlinx.android.synthetic.main.fragment_home.*
import kotlin.properties.Delegates
class HomeFragment : Fragment(R.layout.fragment_home) {
//recyclerview
private val productList = generateProduct()
private var select_price = 0 // gift price
private var select_num = 1 //popup menu value
private fun refreshOutput(){
price_t.text = (select_num*select_price).toString()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = ProductAdapter(productList)
giftRecycleView.adapter = adapter
adapter.setOnItemClickListener{position : Int->
select_price = productList[position].price.toInt()
refreshOutput()
}
giftRecycleView.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)
//popup menu
val popupMenu = PopupMenu(
context,
selectedTv
)
for(i in 0..5){
popupMenu.menu.add(Menu.NONE,i,i,i.toString())
}
//handle menu clicks
popupMenu.setOnMenuItemClickListener { menuItem ->
val i = menuItem.itemId+1
selectedTv.text = i.toString()
select_num = i
refreshOutput()
true
}
//handle menu click to show menu
selectedTv.setOnClickListener {
popupMenu.show()
}
//calculate the total price
refreshOutput()
}
private fun generateProduct(): List<Product>{
val list = ArrayList<Product>()
list.add(Product("5"))
list.add(Product("6"))
list.add(Product("7"))
return list
}
}
If I understood correctly the popup has a value other than textView and this value is used for the calculation. And the problem comes before selecting amout.
You can set a default popup value like here
How to set a default selected option in Android popup menu?
First I have to say something about this piece of code. If you find yourself copy-pasting code like this, you need to step back and simplify it. Your setup of the popup menu could be cut down to this:
//add menu items to popup menu
for (i in 0..4) {
popupMenu.menu.add(Menu.NONE, i, i, (i + 1).toString())
}
//handle menu clicks
popupMenu.setOnMenuItemClickListener { menuItem ->
val i = menuItem.itemId + 1
selectedTv.text = i.toString()
select_num = i
total_price = select_num * select_price
price_t.text = total_price.toString()
true
}
And here you can see the problem. You are only updating the calculated value when the popup menu is clicked, but not when a different view is selected in the adapter. You should create a function that updates the calculation and puts it in the text view, and call them from both listeners (adapter's item click listener and the popup menu listener).
It's kind of weird to do this with local variables and more unusual to define a function inside onViewCreated(). You should promote them to private properties so the function goes outside onViewCreated(). Eliminate the total_price variable because you never use it in a useful way. It will always be out of date once something else changes, so it is not helping you at all. So your code will end up looking like:
private var select_price = 0
private var select_num = 1
private fun refreshOutput() {
price_t.text = (select_num * select_price).toString()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = ProductAdapter(productList)
giftRecycleView.adapter = adapter
adapter.setOnItemClickListener(object :ProductAdapter.onItemClickListener{
override fun onItemClick(position: Int) {
select_price = productList[position].price.toInt()
refreshOutput()
}
})
giftRecycleView.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)
//popup menu
val popupMenu = PopupMenu(
context,
selectedTv
)
for (i in 0..5) {
popupMenu.menu.add(Menu.NONE, i, i, i.toString())
}
//handle menu clicks
popupMenu.setOnMenuItemClickListener { menuItem ->
val i = menuItem.itemId + 1
selectedTv.text = i.toString()
select_num = i
refreshOutput()
true
}
//handle menu click to show menu
selectedTv.setOnClickListener {
popupMenu.show()
}
//calculate the total price
refreshOutput() // show initial value
}
And a couple of tips about Kotlin. You are misusing lateinit for your listener. lateinit is for properties that are guaranteed to be initialized before they are accessed anywhere else in your code. This is mostly only applicable for classes that are instantiated by reflection, and the subclass's code's first entry point is somewhere other than the constructor, like in an Activity's onCreate() or Fragment's onCreateView()/onViewCreated(). This is not true for your Adapter, so by marking the property lateinit, you are only using the keyword to subvert null-safety. The property should simply be nullable, and a null-safe call should be used with it in the one place where you actually use it.
Also, if you define your interface as a fun interface, you can take advantage of lambda syntax.
private var mlistener : onItemClickListener? = null
fun interface onItemClickListener{
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener){
mlistener = listener
}
//...
// In product view holder:
init {
itemView.setOnClickListener {
listener?.onItemClick(absoluteAdapterPosition)
}
}
// In Fragment:
adapter.setOnItemClickListener { position: Int ->
select_price = productList[position].price.toInt()
refreshOutput()
}
And finally, my answer is just explaining how to get your current code working. Really, you should convert the select_price and select_num into LiveDatas or StateFlows in a ViewModel. Then you would use these values to set up the state of your UI elements, and they will persist correctly if the screen is rotated. The way it is now, when the screen rotates, your currently selected price and number will be lost.

How to attach an adapter in fragment?

I use Kotlin in SDK 29.
I would like to make a recyclerView in my fragment. When I run the device, it doesn't crash, the fragment appear but not the Recycler View and I have the following error :
E/RecyclerView: No adapter attached; skipping layout
Here is my code :
Adapter
Import :
import android.content.Context
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.givenaskv1.R
import kotlinx.android.synthetic.main.item_post.view.*
Code :
class PostsAdapter (val context: Context, val posts : List<Post>) :
RecyclerView.Adapter<PostsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = posts.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(posts[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(post: Post) {
itemView.tvUsername.text = post.user?.firstName
itemView.tvDescription.text = post.description
Glide.with(context).load(post.imageUrl).into(itemView.ivPost)
itemView.tvRelativeTime.text = DateUtils.getRelativeTimeSpanString(post.creationTimeMs)
}
}
}
Fragment
Import :
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.givenaskv1.R
import com.example.givenaskv1.models.Post
import com.example.givenaskv1.models.PostsAdapter
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import kotlinx.android.synthetic.main.fragment_flux.*
Code :
private const val TAG = "Flux"
#Suppress("UNREACHABLE_CODE")
class Flux : Fragment() {
private lateinit var firestoreDb : FirebaseFirestore
private lateinit var posts : MutableList<Post>
private lateinit var adapter: PostsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_flux, container, false)
posts = mutableListOf()
adapter = PostsAdapter(requireContext(), posts)
rvPosts.adapter = adapter
rvPosts.layoutManager = LinearLayoutManager(requireContext())
firestoreDb = FirebaseFirestore.getInstance()
val postsReference = firestoreDb.collection("post")
// .limit() indique le nombre de post MAXIMIM a afficher en même temps, pour éviter le lagg
.limit(20)
// .orderBy() filtre selon le critère choisi (ici par ordre chonologique)
.orderBy("creation_time_ms", Query.Direction.DESCENDING)
postsReference.addSnapshotListener{ snapshot, exception ->
if (exception != null || snapshot == null) {
Log.e(TAG, "Exception when querying posts", exception)
return#addSnapshotListener
}
val postList = snapshot.toObjects(Post::class.java)
posts.clear()
posts.addAll(postList)
adapter.notifyDataSetChanged()
for (post in postList) {
Log.i(TAG, "Post ${post}")
}
}
}
Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".Flux.Flux">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvPosts"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="vertical"
/>
</LinearLayout>
Can you please help me ? Thank you !
You should return view at the end of onCreateView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_flux, container, false)
posts = mutableListOf()
adapter = PostsAdapter(requireContext(), posts)
rvPosts = view.findViewById<RecyclerView>(R.id.rvPosts)
rvPosts.layoutManager = LinearLayoutManager(requireContext())
rvPosts.adapter = adapter
firestoreDb = FirebaseFirestore.getInstance()
val postsReference = firestoreDb.collection("post")
// .limit() indique le nombre de post MAXIMIM a afficher en même temps, pour éviter le lagg
.limit(20)
// .orderBy() filtre selon le critère choisi (ici par ordre chonologique)
.orderBy("creation_time_ms", Query.Direction.DESCENDING)
postsReference.addSnapshotListener{ snapshot, exception ->
if (exception != null || snapshot == null) {
Log.e(TAG, "Exception when querying posts", exception)
return#addSnapshotListener
}
val postList = snapshot.toObjects(Post::class.java)
posts.clear()
posts.addAll(postList)
adapter.notifyDataSetChanged()
for (post in postList) {
Log.i(TAG, "Post ${post}")
}
}
return view
}

Kotlin RecyclerView how select first list item after activity load? tried (code below) failed :(

I can select 1st item in RecyclerView (working code below, click on "email" FAB button - boom! 1st selected)
However I cannot get 1st RecyclerView click in code when app starts,
I looked for override fun onViewCreated() but nothing like it for activity,
where can I call selectFirstOnList() after activity & recyclerview fully rendered?
what event fires on activity fully rendered/loaded?
or is my noob kotlin way of thinking flawed? its 99.9% working :(
Thanks in advance for any help :)
SOLUTIUON (code edited to bottom of this post will replace code in ItemListActivity.kt)
postdelay select first (you can see from original code I'd already tried something like this!) PHEW! hope this helps someone :)
ItemListActivity.kt
package ie.dpsystems.asm.list
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import ie.dpsystems.asm.R
import ie.dpsystems.asm.data.Orientation
import ie.dpsystems.asm.data.State
import ie.dpsystems.asm.data.State.Companion.trackLog
import ie.dpsystems.asm.detail.ItemDetailActivity
import ie.dpsystems.asm.detail.ItemDetailFragment
import kotlinx.android.synthetic.main.activity_item_list.*
import kotlinx.android.synthetic.main.item_list_content.view.*
import kotlinx.android.synthetic.main.item_list.*
import android.os.Handler
class ItemListActivity : AppCompatActivity() {
private var twoPane: Boolean = false
private var showToastEvents: Boolean = true
private fun uiIsTwoPane():Boolean{
try{
if (item_detail_container != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
return true
}
}catch(e:Exception)
{
Toast.makeText(this,"E: ${e.toString()}",Toast.LENGTH_SHORT).show()
}
return false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
trackLog(this,"onCreate()")
setContentView(R.layout.activity_item_list)
twoPane = uiIsTwoPane()
setSupportActionBar(toolbar)
toolbar.title = title
fab.setOnClickListener { view -> onListFabClick(view) }
setupRecyclerView(recycleview_list)
refreshUI()
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
trackLog(this,"setupRecyclerView()")
State.dataRows = ListContent.ITEMS
recyclerView.adapter = SimpleItemRecyclerViewAdapter(
this,
twoPane,
this
)
var recycleViewUI = recycleview_list
postAndNotifyAdapter(Handler(), recycleViewUI)
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
trackLog(this,"onConfigurationChanged()")
}
override fun onStart() {
super.onStart()
trackLog(this,"onStart()")
}
override fun onResume() {
super.onResume()
trackLog(this,"onResume() A")
checkOrientationChange()
refreshUI()
trackLog(this,"onResume() B")
}
private fun checkOrientationChange() {
trackLog(this,"checkOrientationChange()")
if (State.lastOrientation != null) {
val thisOrientation = if (twoPane) Orientation.landscape else Orientation.portrate
if (thisOrientation != State.lastOrientation) {
putDetailFragmentOnDetailFragmentHolder()
}
}
}
private fun putDetailFragmentOnDetailFragmentHolder() {
trackLog(this,"putDetailFragmentOnDetailFragmentHolder()")
if(item_detail_container!=null){
val fragment = ItemDetailFragment() //val fragment = ItemDetailFragment().apply {arguments = Bundle().apply {putInt("SOME UNIQUE TAG", selectedItemUniqueID)}}
val container = item_detail_container
container.removeAllViewsInLayout()
supportFragmentManager.beginTransaction().replace(R.id.item_detail_container, fragment).commit()
}
}
override fun onPause() {
super.onPause()
trackLog(this,"onPause()")
}
override fun onStop() {
super.onStop()
trackLog(this,"onStop()")
}
class SimpleItemRecyclerViewAdapter( private val parentActivity: ItemListActivity
,private val twoPane: Boolean
,private val context: Context //private val context = parentActivity.applicationContext
) : RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder>() {
override fun getItemCount(): Int {
return State.dataRows.size
}
override fun onBindViewHolder(recyclerViewRow: ViewHolder, position: Int) {
trackLog(context, "onBindViewHolder()")
val dataThisRow = State.dataRows[position]
dataThisRow.listRowIndex = position
setDataToRecyclerRow(recyclerViewRow, dataThisRow)
recyclerViewRow.itemView.setOnClickListener {
onListItemClick(dataThisRow.uniqueID)
}
if (dataThisRow.uniqueID == State.selectedListItemUniqueId) {
recyclerViewRow.idRow.setBackgroundColor(Color.parseColor("#009688"))
} else {
recyclerViewRow.idRow.setBackgroundColor(Color.WHITE)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
trackLog(context, "onCreateViewHolder()")
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_list_content, parent, false)
return ViewHolder(view, 1)
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
super.onViewAttachedToWindow(holder)
trackLog(context, "onViewAttachedToWindow()")
}
inner class ViewHolder(itemView: View, position: Int) : RecyclerView.ViewHolder(itemView) {
val idView: TextView = itemView.id_text
val contentView: TextView = itemView.content
val idRow = itemView.id_row_linear_layout
}
private fun setDataToRecyclerRow(recyclerViewRow: ViewHolder, data: ListContent.ListItem) {
trackLog(context, "setDataToRecyclerRow(id: ${data.id})")
recyclerViewRow.idView.text = data.id
recyclerViewRow.contentView.text = data.itemTitle
recyclerViewRow.itemView.tag = data
}
private fun onListItemClick(selectedItemUniqueID: Int) {
trackLog(context, "onListItemClick($selectedItemUniqueID)")
State.selectedListItemUniqueId = selectedItemUniqueID
if (twoPane) {
State.lastOrientation = Orientation.landscape
putDetailFragmentOnDetailActivity()
} else {
State.lastOrientation = Orientation.portrate
launchDetailActivity()
}
notifyDataSetChanged()
}
private fun launchDetailActivity() {
trackLog(context, "launchDetailActivity()")
val intent = Intent(
context,
ItemDetailActivity::class.java
) //val intent = Intent(context, ItemDetailActivity::class.java).apply {putExtra(ItemDetailFragment.ARG_ITEM_ID, selectedItemUniqueID)}
context.startActivity(intent)
}
private fun putDetailFragmentOnDetailActivity() {
trackLog(context, "putDetailFragmentOnDetailFragmentHolder()")
val fragment =
ItemDetailFragment() //val fragment = ItemDetailFragment().apply {arguments = Bundle().apply {putInt("SOME UNIQUE TAG", selectedItemUniqueID)}}
val container = parentActivity.item_detail_container
container.removeAllViewsInLayout()
parentActivity.supportFragmentManager.beginTransaction()
.replace(R.id.item_detail_container, fragment).commit()
}
}
private fun onListFabClick(view: View) {
trackLog(this, "onListFabClick()")
selectFirstOnList()
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
private fun refreshUI() {
trackLog(this, "refreshUI()")
var recycleViewUI = recycleview_list
if (State.selectedListItemUniqueId == null) {
selectFirstOnList()
} else {
val selectedListItem: ListContent.ListItem? =
State.findDataRowByUniqueId(State.selectedListItemUniqueId)
if (selectedListItem == null) {
selectFirstOnList()
recycleViewUI.findViewHolderForAdapterPosition(0)?.itemView?.performClick()
} else {
recycleViewUI.getLayoutManager()
?.scrollToPosition(selectedListItem.listRowIndex)
}
}
}
private fun selectFirstOnList() {
trackLog(this, "selectFirstOnList()")
if (twoPane) {
var recycleViewUI = recycleview_list
//recycleViewUI.getLayoutManager()?.scrollToPosition(0)
recycleViewUI.findViewHolderForAdapterPosition(0)?.itemView?.performClick()
}
}
protected fun postAndNotifyAdapter(handler: Handler, recyclerView: RecyclerView) {
trackLog(this, "postAndNotifyAdapter()")
/*
handler.post(Runnable {
if (!recyclerView.isComputingLayout) {
// This will call first item by calling "performClick()" of view.
(recyclerView.findViewHolderForLayoutPosition(0) as RecyclerView.ViewHolder).itemView.performClick()
} else {
postAndNotifyAdapter(handler, recyclerView) //, adapter
}
})
*/
}
}
class State (hold selected on screen rotation/activity changes)
import android.content.Context
import android.util.Log
import android.widget.Toast
import ie.dpsystems.asm.list.ListContent
import java.util.ArrayList
enum class Orientation { portrate, landscape }
class State {
companion object {
public var selectedListItemUniqueId:Int? = null
public var dataRows: MutableList<ListContent.ListItem> = ArrayList()
public var lastOrientation:Orientation? = null
public fun findDataRowByUniqueId(uniqueID:Int?):ListContent.ListItem?{
if(uniqueID==null) return null
return State.dataRows.find { it.uniqueID == uniqueID}
}
public fun trackLog(context: Context, text:String){
//Toast.makeText(context,text, Toast.LENGTH_LONG).show()
Log.d("track",text)
}
}
}
src/main/res/layout-w900dp/item_list.xml (2 pane for tablet)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".list.ItemListActivity">
<!--
This layout is a two-pane layout for list / detail
-->
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recycleview_list"
android:name="ie.dpsystems.asm.ItemListFragment"
android:layout_width="#dimen/item_width"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context="ie.dpsystems.asm.list.ItemListActivity"
tools:listitem="#layout/item_list_content" />
<FrameLayout
android:id="#+id/item_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
item_list_content.xml (RecyclerView per row layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/id_row_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/id_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
</LinearLayout>
object ListContent (to put fake data into list during development)
import java.util.ArrayList
import java.util.HashMap
/**
* Helper class for providing sample itemTitle for user interfaces created by
* Android template wizards.
*
* TODO: Replace all uses of this class before publishing your app.
*/
object ListContent {
/**
* An array of sample (dummy) items.
*/
val ITEMS: MutableList<ListItem> = ArrayList()
/**
* A map of sample (dummy) items, by ID.
*/
val ITEM_MAP: MutableMap<String, ListItem> = HashMap()
private val COUNT = 25
init {
// Add some sample items.
for (i in 1..COUNT) {
addItem(fakeGetRecordFromSqlite(i))
}
}
private fun addItem(item: ListItem) {
ITEMS.add(item)
ITEM_MAP.put(item.id, item)
}
private fun fakeGetRecordFromSqlite(position: Int): ListItem {
return ListItem(position, -1, position.toString(), "Item " + position, fakeGetRecordCollectionFromSqlite(position))
}
private fun fakeGetRecordCollectionFromSqlite(position: Int): String {
val builder = StringBuilder()
builder.append("Details about Item: ").append(position)
for (i in 0..position - 1) {
builder.append("\nMore details information here.")
}
return builder.toString()
}
/**
* A dummy item representing a piece of itemTitle.
*/
data class ListItem(val uniqueID:Int, var listRowIndex:Int, val id: String, val itemTitle: String, val details: String) {
override fun toString(): String = itemTitle
}
}
class ItemDetailFragment (display details in detail fragment)
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ie.dpsystems.asm.R
import ie.dpsystems.asm.data.State
import ie.dpsystems.asm.list.ListContent
import kotlinx.android.synthetic.main.activity_item_detail.*
import kotlinx.android.synthetic.main.item_detail.view.*
/**
* A fragment representing a single Item detail screen.
* This fragment is either contained in a [ItemListActivity]
* in two-pane mode (on tablets) or a [ItemDetailActivity]
* on handsets.
*/
class ItemDetailFragment : Fragment() {
/**
* The dummy itemTitle this fragment is presenting.
*/
private var item: ListContent.ListItem? = null
private var selectedItemUniqueID:Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//arguments?.let { if (it.containsKey(ARG_ITEM_ID)) {val uniqueID = it.getInt(ARG_ITEM_ID)}}
item = State.findDataRowByUniqueId(State.selectedListItemUniqueId)
activity?.toolbar_layout?.title = item?.itemTitle
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.item_detail, container, false)
item?.let {rootView.item_detail.text = it.details}
return rootView
}
}
class ItemDetailActivity (for single pane screen size devices)
import android.content.Intent
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NavUtils
import android.view.MenuItem
import android.view.View
import ie.dpsystems.asm.list.ItemListActivity
import ie.dpsystems.asm.R
import kotlinx.android.synthetic.main.activity_item_detail.*
import kotlinx.android.synthetic.main.activity_item_detail.fab
/**
* An activity representing a single Item detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a [ItemListActivity].
*/
class ItemDetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_item_detail)
setSupportActionBar(detail_toolbar)
fab.setOnClickListener { view -> onListFabClick(view) }
supportActionBar?.setDisplayHomeAsUpEnabled(true) // Show the Up button in the action bar.
putDetailFragmentOnDetailActivity(savedInstanceState)
}
private fun putDetailFragmentOnDetailActivity(savedInstanceState: Bundle?){ // Create the detail fragment and add it to the activity using a fragment transaction.
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
// http://developer.android.com/guide/components/fragments.html
if (savedInstanceState == null) {
val fragment = ItemDetailFragment() //val fragment = ItemDetailFragment().apply {arguments = Bundle().apply {putString("SOME UNIQUE TAG",intent.getStringExtra("SOME UNIQUE TAG"))}}
supportFragmentManager.beginTransaction().add(R.id.item_detail_container, fragment).commit()
}
}
private fun onListFabClick(view: View?) {
if(view!=null) Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
override fun onOptionsItemSelected(item: MenuItem) =
when (item.itemId) {
android.R.id.home -> {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
NavUtils.navigateUpTo(this, Intent(this, ItemListActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
SOLUTIUON
postdelay select first (you can see from original code I'd already tried something like this!) PHEW! hope this helps someone :)
protected fun postAndNotifyAdapter(handler: Handler, recyclerView: RecyclerView) {
trackLog(this, "postAndNotifyAdapter() ${State.selectedListItemUniqueId}")
if (twoPane && State.selectedListItemUniqueId==null) {
Handler().postDelayed({
if (!recyclerView.isComputingLayout) {
trackLog(this, "postAndNotifyAdapter() !recyclerView.isComputingLayout ${State.selectedListItemUniqueId}")
selectFirstOnList()
} else {
postAndNotifyAdapter(handler, recyclerView) //, adapter
}
}, 1000)
}
}
I've edited my original post above to be complete with answer!
I recommend you use an interface to notify when recyclerview is done rendering it's items.
How to know when the RecyclerView has finished laying down the items?

Kotlin read and display data from Google Sheets

Can somebody help me accomplish what I am trying to. I have spent hours watching videos and surfing Google to do it myself. But, I couldn't as there's no help I could find to read just one cell value from Google Sheets and I couldn't also find code for Kotlin.
All what I want is to display the value in cell B2 in my Google sheets in a textview on MainActivity.
I am new to Android app development.
Thanks in advance.
i have code for to get the value from google sheets let me share it to you.
First of all you need to create one spreadsheet and you need to create your api key to get access to spreadsheet api.
MY SpreadSheet data
--> When you create spread sheet in file options -> publish to web. and it will generate a link.
-> get the sheets id from that link. it will be like
https://docs.google.com/spreadsheets/d/your-id-//edit#gid=0
--> On given url you have to put your sheets id sheet name and the api key that you have generated from google console
From generated url you can get the json format of your data into spreadsheet.
Your url will look like this.
https://sheets.googleapis.com/v4/spreadsheets/YOUR_SHEET_ID/values/YOUR_SHEET_NAME?alt=json&key=YOUR_API_KEY
Open this url into browser and get the json format of your data from spreadsheet.
After getting the data
Here is the code to retrive the data from spreadsheet.
first you need a model class to get the data from json.
class model {
// variables for our first name,
// last name, email and avatar
private var first_name: String? = null
private var last_name: String? = null
private var email: String? = null
constructor(first_name: String, last_name: String, email: String){
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
}
fun getFirst_name(): String? {
return first_name
}
fun setFirst_name(first_name: String?) {
this.first_name = first_name
}
fun getLast_name(): String? {
return last_name
}
fun setLast_name(last_name: String?) {
this.last_name = last_name
}
fun getEmail(): String? {
return email
}
fun setEmail(email: String?) {
this.email = email
}
}
BaseModel.kt
class BaseModel {
#SerializedName("range")
#Expose
private var range: String? = null
#SerializedName("majorDimension")
#Expose
private var majorDimension: String? = null
#SerializedName("values")
#Expose
private var values: List<List<model?>?>? = null
fun getRange(): String? {
return range
}
fun setRange(range: String?) {
this.range = range
}
fun getMajorDimension(): String? {
return majorDimension
}
fun setMajorDimension(majorDimension: String?) {
this.majorDimension = majorDimension
}
fun getValues(): List<List<model?>?>? {
return values
}
fun setValues(values: List<List<model?>?>?) {
this.values = values
}
}
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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idRVUsers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/user_rv_item" />
<!--we are adding progress bar for thepurpose of loading-->
<ProgressBar
android:id="#+id/idPBLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
user_rv_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="wrap_content"
android:elevation="8dp"
app:cardCornerRadius="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp">
<!--image view for displaying user image-->
<ImageView
android:id="#+id/idIVUser"
android:layout_width="100dp"
android:src="#drawable/ic_launcher_foreground"
android:layout_height="100dp"
android:layout_margin="10dp" />
<!--text view for displaying first name-->
<TextView
android:id="#+id/idTVFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toEndOf="#id/idIVUser"
android:layout_toRightOf="#id/idIVUser"
android:text="First Name"
android:textColor="#color/black"
android:textSize="15sp" />
<!--text view for displaying last name-->
<TextView
android:id="#+id/idTVLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/idTVFirstName"
android:layout_marginTop="10dp"
android:layout_toEndOf="#id/idIVUser"
android:layout_toRightOf="#id/idIVUser"
android:text="Last Name"
android:textColor="#color/black"
android:textSize="15sp" />
<!--text view for displaying user email-->
<TextView
android:id="#+id/idTVEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/idTVLastName"
android:layout_marginTop="10dp"
android:layout_toEndOf="#id/idIVUser"
android:layout_toRightOf="#id/idIVUser"
android:text="Email"
android:textColor="#color/black"
android:textSize="15sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
rv_adapter.kt
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class UserRVAdapter(modelArraylist: ArrayList<model>) :
RecyclerView.Adapter<UserRVAdapter.ViewHolder>() {
// variable for our array list and context.
private val userModalArrayList: ArrayList<model> = modelArraylist
private val context: Context? = null
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val firstNameTV: TextView? = itemView.findViewById(R.id.idTVFirstName)
var lastNameTV: TextView? = itemView.findViewById(R.id.idTVLastName)
var emailTV: TextView? = itemView.findViewById(R.id.idTVEmail)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View =
LayoutInflater.from(parent.context).inflate(R.layout.user_rv_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// getting data from our array list in our modal class.
// getting data from our array list in our modal class.
val userModal: model = userModalArrayList[position]
// on the below line we are setting data to our text view.
// on the below line we are setting data to our text view.
holder.firstNameTV?.setText(userModal.getFirst_name())
holder.lastNameTV?.setText(userModal.getLast_name())
holder.emailTV?.setText(userModal.getEmail())
}
override fun getItemCount(): Int {
return userModalArrayList.size
}
}
MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONException
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
private var userModalArrayList: ArrayList<model>? = null
private var userRVAdapter: UserRVAdapter? = null
private var userRV: RecyclerView? = null
private var loadingPB: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userModalArrayList = ArrayList()
userRV = findViewById(R.id.idRVUsers)
loadingPB = findViewById(R.id.idPBLoading)
getDataFromAPI()
}
private fun getDataFromAPI() {
val url=
"https://sheets.googleapis.com/v4/spreadsheets/YOUR_SHEET_ID/values/YOUR_SHEET_NAME?alt=json&key=YOUR_API_KEY"
val queue = Volley.newRequestQueue(this#MainActivity)
val jsonObjectRequest =
JsonObjectRequest(
Request.Method.GET,
url,
null,
object : Response.Listener<JSONObject> {
override fun onResponse(response: JSONObject) {
loadingPB!!.visibility = View.GONE
try {
// val feedObj = response.getJSONObject("")
val entryArray = response.getJSONArray("values")
for (i in 1 until entryArray.length()) {
val entryObj = entryArray.getJSONArray(i)
val firstName =
entryObj[2].toString()
val lastName = entryObj[3].toString()
// entryObj.getJSONObject("gsx\$lastname").getString("\$t")
val email = entryObj[1].toString()
userModalArrayList!!.add(model(firstName, lastName, email))
// passing array list to our adapter class.
userRVAdapter = UserRVAdapter(userModalArrayList!!)
// setting layout manager to our recycler view.
userRV!!.layoutManager = LinearLayoutManager(this#MainActivity)
// setting adapter to our recycler view.
userRV!!.adapter = userRVAdapter
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
},
object : Response.ErrorListener {
override fun onErrorResponse(error: VolleyError?) {
// handline on error listener method.
Toast.makeText(this#MainActivity, "Fail to get data..", Toast.LENGTH_SHORT)
.show()
}
})
queue.add(jsonObjectRequest);
}
}
You can use this code to get data from your whole google spread sheet.
I suggest making google sheet public, then you can access it for example as csv or in other formats, but csv is simplest. You can construct url based on sheet id:
val url = "https://docs.google.com/spreadsheets/d/e/${id}/pub?output=csv"
You can get contents for example using ktor:
suspend fun getUrlAsString(url: String): String {
val client = HttpClient(Android) {
}
return client.get<String>(url)
}
Example on how to parse csv, but you can use some library or parse text yourself, it's pretty simple:
fun parseCsv(text: String): List<Map<String, String>> {
val reader = CSVReaderBuilder(StringReader(text))
.build()
val lines = reader.readAll()
val firstLine = lines.removeAt(0)
val result = lines.map { line ->
firstLine.mapIndexed { index, label ->
label to line[index]
}.toMap()
}
if (result.size > 4)
println(result[4])
return result
}