I'm working on an android app that interfaces with a google sheet. I was following the api documentation for writing values to certain cells but I'm getting this error here:
Caused by: java.io.IOException: The Application Default Credentials are not available.
I have made sure to set my credentials in google cloud platform for my project and downloaded the .json file to src\main\resources in my android studio project.
here is the code that is supposed to write the data:
package com.example.frcscout22
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import com.google.api.client.http.HttpRequestInitializer
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.sheets.v4.Sheets
import com.google.api.services.sheets.v4.SheetsScopes
import com.google.api.services.sheets.v4.model.ValueRange
import com.google.auth.http.HttpCredentialsAdapter
import com.google.auth.oauth2.GoogleCredentials
import java.util.*
class Data : Fragment(R.layout.fragment_data) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val spinner = view.findViewById<Spinner>(R.id.defense_spinner)
val aa = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, resources.getStringArray(R.array.Defenses))
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = aa
view.findViewById<Spinner>(R.id.defense_spinner).visibility = View.GONE
view.findViewById<TextView>(R.id.textView6).visibility = View.GONE
view.findViewById<EditText>(R.id.Team_Defended).visibility = View.GONE
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater!!.inflate(R.layout.fragment_data, container, false)
val checkBox = view.findViewById<CheckBox>(R.id.checkBox)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
view.findViewById<Spinner>(R.id.defense_spinner).visibility = View.VISIBLE
view.findViewById<TextView>(R.id.textView6).visibility = View.VISIBLE
view.findViewById<EditText>(R.id.Team_Defended).visibility = View.VISIBLE
} else {
view.findViewById<Spinner>(R.id.defense_spinner).visibility = View.GONE
view.findViewById<TextView>(R.id.textView6).visibility = View.GONE
view.findViewById<EditText>(R.id.Team_Defended).visibility = View.GONE
}
}
val clear = view.findViewById<Button>(R.id.button2)
clear.setOnClickListener(View.OnClickListener {
view.findViewById<EditText>(R.id.Match_Number).setText("")
view.findViewById<EditText>(R.id.Team_Number).setText("")
view.findViewById<EditText>(R.id.Auto_Points).setText("")
view.findViewById<EditText>(R.id.Teleop_Points).setText("")
view.findViewById<EditText>(R.id.Endgame_Points).setText("")
view.findViewById<EditText>(R.id.Team_Defended).setText("")
view.findViewById<Spinner>(R.id.defense_spinner).setSelection(0)
view.findViewById<CheckBox>(R.id.checkBox).isChecked = false
})
val table : MutableList<MutableList<Any>> = mutableListOf(mutableListOf("test", "test2"))
val values = ValueRange()
values.majorDimension = "ROWS"
values.setValues(table)
val button = view.findViewById<View>(R.id.button)
button.setOnClickListener(View.OnClickListener {
setRow("1fs1U9-LMmkmQbQ2Kn-rNVHIQwh6_frAbwaTp7MSyDIA", "Sheet1!A1:B1", values)
})
// Return the fragment view/layout
return view
}
private fun setRow(spreadSheetID: String, range: String, values: ValueRange) {
val credentials: GoogleCredentials = GoogleCredentials.getApplicationDefault().createScoped(
Collections.singleton(
SheetsScopes.SPREADSHEETS))
val requestInitializer: HttpRequestInitializer = HttpCredentialsAdapter(credentials)
val service: Sheets = Sheets.Builder(NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer).setApplicationName("FRCScout22").build()
service.spreadsheets().values().update(spreadSheetID, range, values)
.setValueInputOption("USER_ENTERED")
.execute();
}
}
Does anyone know why I may be getting this error? Thanks!!
Application Default Credentials (ADC) is a process that looks for the credentials in various places including the env var GOOGLE_APPLICATION_CREDNTIALS.
If GOOGLE_APPLICATION_CREDNTIALS is unset ADC fails and raises an error.
Related
I have fragment which showing weather for 10 days with getting geolocation city and show exactly weather for this city for 10 days.
I have problem initialization with RecyclerView and Viewmodel.
Also I use Hilt to provide dependencies.
My goal is showing weather by location (already have permission) for 10 days.
import androidx.lifecycle.LiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import db.entities.WeatherData
#HiltViewModel
interface ForecastViewmodel {
val dataforecast:LiveData<List<WeatherData>>
val city : LiveData<String>
val isRefreshing:LiveData<Boolean>
fun onRefresh()
}
#HiltViewModel
class ForecastViewmodelImpl(private val repository: ForecastRepository,
private val day: Day
) : ForecastViewmodel,
ViewModel(){
override val dataforecast = MutableLiveData<List<WeatherData>>()
override val city = MutableLiveData(day.city)
override val isRefreshing = MutableLiveData(true)
init {
loadForecast()
}
private fun loadForecast() {
isRefreshing.value = true
viewModelScope.launch {
try {
val data = repository.getForecast(day.days)
Timber.d("size is ${data}")
}catch (e:Exception){
Timber.e(e)
}
isRefreshing.value = false
}
}
override fun onRefresh() = loadForecast()
private fun Forecastday.toWeatherData() = WeatherData(
date = date,
temp = "${temp.roundToInt()}℃"
)
}
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.testtaskweatherappkevychsol.R
import db.entities.WeatherData
class WeatherRecView:RecyclerView.Adapter<WeatherRecView.WeatherHolder>() {
var listweather = emptyList<WeatherData>()
class WeatherHolder(view:View):RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): WeatherHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.daily_weather_layout,
parent,false)
return WeatherHolder(view)
}
override fun onBindViewHolder(
holder: WeatherHolder,
position: Int
) {
holder.itemView.findViewById<TextView>(R.id.Dateitem).text = listweather[position].date
holder.itemView.findViewById<TextView>(R.id.tempitem).text = listweather[position]
.temp.toString()
}
override fun getItemCount(): Int {
return listweather.size
}
fun addlistintoUI(list: List<WeatherData>){
listweather = list
}
}
data class WeatherData(
val temp:String,
val date:String
)
import RecyclerView.WeatherRecView
import Viewmodel.ForecastViewmodel
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.testtaskweatherappkevychsol.R
import com.example.testtaskweatherappkevychsol.databinding.FragmentWeatherBinding
import dagger.hilt.android.AndroidEntryPoint
#AndroidEntryPoint
class WeatherAtTheLifeMomentFragment : Fragment(R.layout.fragment_weather){
lateinit var recview:WeatherRecView
private var binding : FragmentWeatherBinding? = null
lateinit var viewmodel:ForecastViewmodel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentWeatherBinding.inflate(inflater,container,false)
this.binding = binding
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(binding){
this!!.refreshbt.setOnClickListener { viewmodel.isRefreshing }
containerlistweather.adapter = recview
containerlistweather.addItemDecoration(DividerItemDecoration(containerlistweather.context,
(containerlistweather
.layoutManager as LinearLayoutManager).orientation))
with(viewmodel){
dataforecast.observe(viewLifecycleOwner) { recview.listweather = it }
City.text = city.toString()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
}
lateinit property recview has not been initialized
you are getting this issue as you are trying to access lateinit property recview without initialising it
in WeatherAtTheLifeMomentFragment
From
containerlistweather.adapter = recview
To
recview = WeatherRecView() // initialise recview variable by creating instance of your adapter
containerlistweather.layoutManager = LinearLayoutManager(context) // not sure you have set layout manager in your xml so just adding it in your code as it is necessary to use
containerlistweather.adapter = recview
Also you have create method addlistintoUI in WeatherRecView class so use it and make below mentioned changes to load your data
in WeatherAtTheLifeMomentFragment class
From
dataforecast.observe(viewLifecycleOwner) { recview.listweather = it }
To
dataforecast.observe(viewLifecycleOwner) { recview.addlistintoUI(it) }
in WeatherRecView class
From
fun addlistintoUI(list: List<WeatherData>){
listweather = list
}
To
fun addlistintoUI(list: List<WeatherData>){
listweather.addAll(list)
notifyDataSetChanged()
}
```
I would like to navigate between fragments using a textView inside a recyclerview.
Currently I am successfully navigating between fragments using the item, but I would like to go further and navigate using the individual textViews within an item.
The recyclerview is inflated from a local room database.
Below is my adapter
package com.benb.inventory
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.benb.inventory.data.Item
import com.benb.inventory.data.getFormattedPrice
import com.benb.inventory.databinding.ItemListItemBinding
class ItemListAdapter(private val onItemClicked: (Item) -> Unit) :
ListAdapter<Item, ItemListAdapter.ItemViewHolder>(DiffCallback) {
class ItemViewHolder(internal var binding: ItemListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Item) {
binding.apply {
itemName.text = item.itemName
itemPrice.text = item.getFormattedPrice()
itemShop.text = item.shop.toString()
itemShop.setOnClickListener{
val shopName = itemShop.text.toString()
Toast.makeText(root.context, "Clicked: ${item.shop}", Toast.LENGTH_SHORT ).show()
}
}
}
}
companion object {
private val DiffCallback = object : DiffUtil.ItemCallback<Item>() {
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem.itemName == newItem.itemName
}
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ItemListAdapter.ItemViewHolder {
return ItemViewHolder(ItemListItemBinding.inflate(LayoutInflater.from(parent.context)))
}
override fun onBindViewHolder(holder: ItemListAdapter.ItemViewHolder, position: Int) {
val current = getItem(position)
holder.itemView.setOnClickListener {
onItemClicked(current)
}
holder.binding.itemShop.setOnClickListener {
onItemClicked(current)
val shopName = current.shop
fun showShopList(shopName: String) {
val shopName = holder.binding.itemShop.text.toString()
val action = ItemListFragmentDirections.actionItemListFragmentToShopItemFragment(shopName)
}
}
holder.bind(current)
}
}
This is the fragment that contains the list
package com.benb.inventory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.benb.inventory.databinding.ItemListFragmentBinding
import kotlinx.coroutines.InternalCoroutinesApi
#InternalCoroutinesApi
class ItemListFragment : Fragment() {
#InternalCoroutinesApi
private val viewModel: InventoryViewModel by activityViewModels {
InventoryViewModelFactory(
(activity?.application as InventoryApplication).database.itemDao()
)
}
private var _binding: ItemListFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ItemListFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = ItemListAdapter {
val action = ItemListFragmentDirections.actionItemListFragmentToItemDetailFragment(it.id)
this.findNavController().navigate(action)
}
binding.recyclerView.adapter = adapter
viewModel.allItems.observe(this.viewLifecycleOwner) {items ->
items.let {
adapter.submitList(it)
}
}
binding.itemShop.setOnClickListener{
val shop = binding.itemShop.text.toString()
val action = ItemListFragmentDirections.actionItemListFragmentToShopItemFragment(shop)
viewModel.retrieveShopItems(shop)
this.findNavController().navigate(action)
}
binding.recyclerView.layoutManager = LinearLayoutManager(this.context)
binding.floatingActionButton.setOnClickListener {
val action = ItemListFragmentDirections.actionItemListFragmentToAddItemFragment(
getString(R.string.add_fragment_title)
)
this.findNavController().navigate(action)
}
}
}
For clarity this is what the inflated recyclerview looks like, it can contain many items, I have only added one.
At the moment if I click anywhere on the item it takes you to a screen with more detail about the fragment.
[A screenshot of the recycler view][1]
I would like to be able to navigate to a specific fragment depending on the textView clicked.
For example one fragment that only contains other products from the same shop.
As you may notice, I have been able to add an onClickListener in the ViewHolder class, it creates a Toast.
I have not had success in using the same onClickListener to navigate.
Thank you very much.
P.S. Any other advice is welcome, particularly if anyone knows what the #internalcoroutinesAPI thing is about please tell me!
[1]: https://i.stack.imgur.com/k6Td3.png
I'm using Kotlin for my app.
I have a problem I can't resolve.
I'm using a RecyclerView inside a fragment that show a Grid with 2 items per row.
Inside each item there are text and image loaded from Firebase.
Everything works perfectly. But, I don't know why, randomly, the images disapear and return a white element. The text doesn't changes, only the image changes.
There is two screens, just few seconds appart. In the first one everything is ok, it shows 4 éléments. Then I restart the app and 3 of the 4 images disapear (second screen). Only the last load to and from Firebase stays.
Inside the code, I'm using a data class named DataClassArticle, an adapter named ArticleAdapter and the fragment named Flux.
1 - First screen
2 - Second sceen
3 - Firebase
4 - Data Class
5 - Adapter
6 - Fragment
1 - FIRST SCREEN (EVERYTHING WORK) :
2- SECOND SCREEN (3 OF THE 4 IMAGES DISAPEAR) :
3 - FIREBASE (RETURNING : DESCRIPTION, PRIXVENTE, TITREVENTE, ZONE, PHOTO)
4- DATA CLASS
data class DataClassArticle(
var titrevente: String? = null,
var prixvente: String? = null,
var zone: String? = null,
var photo: String? = null
)
5- ADAPTER
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.givenaskv1.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
class ArticleAdapter(private var articleList: ArrayList<DataClassArticle>) : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {
val TAG = "TAG"
var dataList = emptyList<DataClassArticle>()
internal fun setDataList(dataList : List<DataClassArticle>) {
this.dataList = dataList
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var articleImage : ImageView
var articleTitle : TextView
var articlePrice : TextView
var articleLocalisation : TextView
init {
articleImage = itemView.findViewById(R.id.articleImage)
articleTitle = itemView.findViewById(R.id.titreArticle)
articlePrice = itemView.findViewById(R.id.prixArticle)
articleLocalisation = itemView.findViewById(R.id.nomVilleArticle)
val myId = FirebaseAuth.getInstance().uid
com.example.givenaskv1.Map.dbref = FirebaseDatabase.getInstance().getReference("Vente")
com.example.givenaskv1.Map.dbref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (missionSnapshot in snapshot.children) {
// if (missionSnapshot.child("uid").value.toString() == myId) {
val test = missionSnapshot.child("uid").value.toString()
Log.d(TAG, "Ceci est l'UID : ${test}.")
// }
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.post_vente, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ArticleAdapter.ViewHolder, position: Int) {
val data = articleList[position]
holder.articleTitle.text = data.titrevente
holder.articlePrice.text = data.prixvente
holder.articleLocalisation.text = data.zone
Picasso.get().load(data.photo).into(holder.articleImage)
}
override fun getItemCount() : Int {
return articleList.size
}
}
6- FRAGMENT
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.GenericTransitionOptions.with
import com.bumptech.glide.Glide.with
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions.with
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.with
import com.example.givenaskv1.R
import com.google.firebase.database.*
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_flux.*
import kotlinx.android.synthetic.main.fragment_notification.*
import kotlinx.android.synthetic.main.post_vente.*
private const val TAG = "TAG"
class Flux : Fragment() {
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<ArticleAdapter.ViewHolder>? = null
private lateinit var dbref : DatabaseReference
private lateinit var userRecyclerview : RecyclerView
private lateinit var userArrayList : ArrayList<DataClassArticle>
private lateinit var articleAdapter: ArticleAdapter
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)
}
override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {
super.onViewCreated(itemView, savedInstanceState)
// RvPosts = le recyclerview
btnPublierVente.setOnClickListener {
val bottomSheet = BottomsheetVentes()
bottomSheet.show(fragmentManager!!, "BottomSheet")
}
rvPosts.apply {
userRecyclerview = findViewById(R.id.rvPosts)
userRecyclerview.setHasFixedSize(true)
userArrayList = arrayListOf<DataClassArticle>()
layoutManager = LinearLayoutManager(activity)
rvPosts.setLayoutManager(GridLayoutManager(this.context, 2))
getUserData()
}
}
private fun getUserData() {
dbref = FirebaseDatabase.getInstance().getReference("Vente")
dbref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (userSnapshot in snapshot.children){
val user = userSnapshot.getValue(DataClassArticle::class.java)
userArrayList.add(user!!)
userRecyclerview.adapter = ArticleAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
Thank you guys for your help.
Have a good day !
I'm trying to implement left and right buttons on the home Fragment of my app, which should scroll to the next card of my RecyclerView. To do this I need to determine the current position of the view so that I can smooth scroll to this position +-1. But helper.findSnapView(linearLayoutManager) always returns null. When this should be fetched there is a
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on ViewConfiguration
in the logcat, which I think is causing the problem. But searching online doesn't yield anything. The code is below. Please try to help me to understand the issue.
package com.example.storybook
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper
import com.example.storybook.Model.Book
import com.example.storybook.Utils.MarginItemDecoration
import com.example.storybook.Utils.RecyclerViewAdapter
import kotlinx.android.synthetic.main.fragment.*
class Fragment : Fragment(), View.OnClickListener {
private var mBooks = mutableListOf<Book>()
private val helper: SnapHelper = LinearSnapHelper()
private val linearLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val listOfBookFilenames: Array<String> = context?.assets?.list("PDFs")!!
for (filename in listOfBookFilenames) {
val tempBook = Book(filename)
mBooks.add(tempBook)
}
return inflater.inflate(R.layout.fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
books_recycler.apply {
layoutManager = linearLayoutManager
adapter = RecyclerViewAdapter(mBooks, context)
}
books_recycler.addItemDecoration(MarginItemDecoration(65))
helper.attachToRecyclerView(books_recycler)
left_button.setOnClickListener {onClick(left_button)}
right_button.setOnClickListener {onClick(right_button)}
}
override fun onClick(view: View) {
val snapView: View? = helper.findSnapView(linearLayoutManager)
var currentFocusPosition = RecyclerView.NO_POSITION
if (snapView == null) {
println("View is null")
} else {
currentFocusPosition = linearLayoutManager.getPosition(snapView)
}
when(view) {
right_button -> books_recycler.smoothScrollToPosition(currentFocusPosition + 1)
left_button -> books_recycler.smoothScrollToPosition(currentFocusPosition - 1)
}
}
}
I have already tried declaring the snapHelper and linearLayoutManagers locally, within the onViewCreated and onClick methods, and it seems to make no difference. This is my first ever app, so there might be a lot I don't understand.
Despite having tried every configuration several times, and rebuilding over an over again, I rebuilt just one more time with the above configuration and it just worked. Sometimes it works out that way.
If you're here from the future and you're having the same problem, try declaring your snapHelper and linearLayoutManager as private values outside the functions and try rebuilding again.
I'm trying to return back to a previous fragment from an activity but I cannot get the functionality to work.
Here is the relevant code from my activity class:
fun previousSubCountryListButtonClicked(view: View) {
val fragmentManager = supportFragmentManager
fragmentManager.popBackStack(R.id.navigation_scotland, POP_BACK_STACK_INCLUSIVE)
}
and here is my fragment class:
package com.riverstonetech.gositeuk.ui.scotland
import android.content.Intent
import android.content.Intent.getIntent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ProgressBar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.google.firebase.firestore.FirebaseFirestore
import com.riverstonetech.gositeuk.CountriesActivity
import com.riverstonetech.gositeuk.R
import com.riverstonetech.gositeuk.RegionActivity
import kotlinx.android.synthetic.main.fragment_scotland.*
class ScotlandFragment : Fragment() {
// Access a Cloud Firestore instance
val db = FirebaseFirestore.getInstance()
lateinit var adapter : ArrayAdapter<String>
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_scotland, container, false)
(requireActivity() as CountriesActivity).initializeCustomActionBar(R.drawable.scotland_flag, R.string.title_regions)
var regions : ArrayList<String>
val docRef = db.collection("UKSites").document("Scotland")
val progressBar: ProgressBar = root.findViewById(R.id.regionsLoadingProgressBar)
docRef.get()
.addOnSuccessListener { document ->
progressBar?.visibility = ProgressBar.VISIBLE
if (document != null) {
regions = document.get("Regions") as ArrayList<String>
adapter = ArrayAdapter(requireContext(), R.layout.list_item, regions)
regionsListView.adapter = adapter
regionsListView.setOnItemClickListener { parent, view, position, id ->
val intent = Intent(activity!!, RegionActivity::class.java)
intent.putExtra("SUB_COUNTRY", regions[position])
startActivity(intent)
}
progressBar?.visibility = ProgressBar.GONE
} else {
Log.d("Debug", "No such document")
}
}
.addOnFailureListener { exception ->
Log.d("Debug", "get failed with ", exception)
}
return root
}
}
I am struggling to understand the official documentation on Android so I would appreciate any help possible. Do I need to add a transaction in my fragment class?
I used finish() instead of writing code to manipulate a fragment manager.