firebase data to recyclerview in fragment - android

This is my first time building an application and I have a problem with making a Recyclerview in a fragment with data from Firebase firestore & storage.
java.lang.NullPointerException: recycle_view must not be null
this is my data class
data class Wallitem (
var title:String,
var image:String,
var ref:String,
var price:String,
var students:String
)
and this is my adapter.kt
class WallAdapter(private var items: ArrayList<Wallitem>, private val context: Context) :
RecyclerView.Adapter<WallAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
Glide.with(context).load(item.image).into(holder.titleImage)
holder.titleTextView.text = item.title
holder.itemView.setOnClickListener {
val i = Intent(context, CoursePage::class.java)
val courseName: String = item.title
val image: String = item.image
val ref: String = item.ref
val price: String = item.price
val students: String = item.students
i.putExtra("courseName", courseName)
i.putExtra("courseImage", image)
i.putExtra("ref", ref)
i.putExtra("coursePrice", price)
i.putExtra("courseStudents", students)
context.startActivity(i)
}
}
override fun getItemCount(): Int {
return items.size
}
class ViewHolder(view: View?) : RecyclerView.ViewHolder(view!!) {
val titleImage:ImageView = view!!.findViewById(R.id.titleImageView)
val titleTextView:TextView = view!!.findViewById(R.id.titleTextView)
}
}
and this is my Fragment.kt (onCreateView part)
private lateinit var adapter: WallAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
val items:ArrayList<Wallitem> = ArrayList()
recycle_view.layoutManager = LinearLayoutManager(view.context, RecyclerView.HORIZONTAL,false)
adapter = WallAdapter(items,view.context)
val db : FirebaseFirestore = FirebaseFirestore.getInstance()
val storage : FirebaseStorage = FirebaseStorage.getInstance()
storage.maxDownloadRetryTimeMillis = 60000
storage.maxOperationRetryTimeMillis = 10000
progressBar.visibility = View.VISIBLE
LoadingTextView.visibility = View.VISIBLE
db.collection("courses").get()
.addOnSuccessListener {documents ->
for(document: QueryDocumentSnapshot in documents){
val wallItem = document.toObject(Wallitem::class.java)
//got title images
val storageRef: StorageReference = storage.reference.child("courses").child("images").child(document.id)
storageRef.list(1).addOnCompleteListener {result ->
val items:List<StorageReference> = result.result!!.items
//got first elements from the list to set title image
items.first().downloadUrl.addOnSuccessListener {
Log.d("storage " ,"$it")
wallItem.image = it.toString()
wallItem.ref = document.id
wallItem.title = document["courseName"].toString()
wallItem.price = document["price"].toString()
wallItem.students = document["students"].toString()
//if you need you may sort
recycle_view.adapter = adapter
}
}
items.add(wallItem)
}
}.addOnFailureListener {
Log.d("fail","Error getting document $it")
}.addOnCompleteListener {
progressBar.visibility = View.GONE
LoadingTextView.visibility = View.GONE
}
return view
}

Related

RecyclerView load only one item

Here RecyclerView loads only one item however the loops works prefect but with RecyclerView loads only one item and not load all items
.........................................................................................................................................................................................................................................
GetJson.kt
class GetJson : AppCompatActivity() {
lateinit var recyclerView: RecyclerView
var arrayList = ArrayList<JsonModel>()
private var requestQueue : RequestQueue? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_get_json)
recyclerView = findViewById(R.id.recyclerView2)
recyclerView.layoutManager = LinearLayoutManager(this)
val getButton : Button = findViewById(R.id.ShowButtonJson)
requestQueue = Volley.newRequestQueue(this)
getButton.setOnClickListener {
getFromServer()
}
}
fun getFromServer(){
val url = "http://..../testapp/getjson.php"
val request = JsonObjectRequest(Request.Method.GET,url,null, {
response -> try {
val jsonArray = response.getJSONArray("names")
for (i in 0 until jsonArray.length()){
val name = jsonArray.getJSONObject(i)
val firstname = name.getString("firstname")
val middlename = name.getString("middlename")
val lastname = name.getString("lastname")
arrayList.add(JsonModel(firstname,middlename,lastname))
}
val namesAdapter = jsonAdapter(arrayList)
recyclerView.adapter = namesAdapter
namesAdapter.notifyDataSetChanged()
} catch (e: JSONException){
e.printStackTrace()
}
}, { response -> response.printStackTrace()
})
requestQueue?.add(request)
}
}
jsonAdapter.kt
class jsonAdapter(val data : List<JsonModel>) : RecyclerView.Adapter<jsonAdapter.ViewHolder>() {
class ViewHolder(view : View) : RecyclerView.ViewHolder(view) {
val firstnameText : TextView = view.findViewById(R.id.firstnameView)
val middlenameText : TextView = view.findViewById(R.id.middleNameView)
val lastnameText : TextView = view.findViewById(R.id.lastNameView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): jsonAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.jsonlist,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: jsonAdapter.ViewHolder, position: Int) {
val namesModel = data[position]
holder.firstnameText.text = namesModel.firstname
holder.middlenameText.text = namesModel.middlename
holder.lastnameText.text = namesModel.lastname
}
override fun getItemCount(): Int {
return data.size
}
}

List items don't come to screen but printed on console

I am trying to parse website using Jsoup. When I run the app, the parsed items come to console, I mean with println statements, but the list of items doesn't come to recyclerview of the fragment, just a blank screen appears. The code part is long, I am pasting the whole fragment(with recyclerview) and adapter codes here. Any help is appreciated.
Adapter Class:
class ExampleAdapter : RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>() {
// ExampleAdapter(private val exampleList: List<Books>)
private val exampleList = mutableListOf<Books>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.example_item, parent, false)
return ExampleViewHolder(itemView)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
// val currentItem = exampleList[position]
// holder.imageView.setImageResource(currentItem.imageResource)
// holder.textView1.text = currentItem.title
// holder.textView2.text = currentItem.description
// holder.textView3.text = currentItem.additionalInfo
holder.bind(exampleList[position])
}
override fun getItemCount(): Int = exampleList.size
class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView: ImageView = itemView.row_img
val textView1: TextView = itemView.row_tv_title
val textView2: TextView = itemView.row_tv_description
val textView3: TextView = itemView.row_tv_additional_info
fun bind(books: Books) {
textView1.text = books.title
textView2.text = books.description
Picasso.with(itemView.context)
.load(books.imageResource)
.transform(CropSquareTransformation())
.into(imageView)
textView3.text = books.additionalInfo
// link = books.linkDetails
}
}
//exampleList class içindeki val değerlerini silmeyince unresolved reference hatası veriyor:
fun set(list: MutableList<Books>) {
this.exampleList.clear()
this.exampleList.addAll(list)
notifyDataSetChanged()
}
}
class CropSquareTransformation : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = Math.min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val result = Bitmap.createBitmap(source, x, y, size, size)
if (result != source) {
source.recycle()
}
return result
}
override fun key(): String {
return "square()"
}
Fragment Class:
class ListBooksFragment : Fragment() {
private lateinit var adapter: ExampleAdapter
private val url ="https://openlibrary.org/search?q=men&mode=everything"
private val exampleList = mutableListOf<Books>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
recycler_view.layoutManager = LinearLayoutManager(this.context)
adapter = ExampleAdapter()
recycler_view.adapter = ExampleAdapter()
GlobalScope.launch {
getData()
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list_books, container, false)
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
ListBooksFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
private fun getData(){
val list = ArrayList<Books>()
try {
val document = Jsoup.connect(url).get()
val elements = document.select("li.searchResultItem")
for (i in 0 until elements.size) {
val title = elements.select("div.resultTitle")
.select("a.results")
.eq(i)
.text()
println("title = " + title.toString())
// AUTHOR:
// val author = elements.select("span.bookauthor")
// .select("a.results")
// .eq(i)
// .text()
val description = elements.select("span.bookauthor")
.select("a.results")
.eq(i)
.text()
println("description = " + description.toString())
val linkImage = "https://www.tutorialspoint.com/images/QAicon.png"
// document.baseUri() +
// elements.select("div[class=bookcover]")
// .select("img")
// .eq(i)
// .attr("src")
val additionalInfo = elements.select("span.resultPublisher")
.select("span.publishedYear")
.eq(i)
.text()
println("additionalInfo = " + additionalInfo.toString())
exampleList.add(Books(imageResource = R.drawable.ic_launcher_background, title, description, additionalInfo))
//Below 2 lines are just for another approach
val item = Books(imageResource = R.drawable.ic_launcher_background, title, description, additionalInfo)
list += item
}
GlobalScope.launch(Dispatchers.Main) {
adapter.set(exampleList)
}
} catch (e: IOException) {
Log.e("TEST EXCEPTION:::: ", e.message.toString())
}
}
}
You are loading the list into an adapter instance which is not associated with the RecyclerView, if you look closely in onActivityCreated, you will see that you are doing
adapter = ExampleAdapter() // New instance of ExampleAdapter assigned to adapter property
recycler_view.adapter = ExampleAdapter()// New instance of ExampleAdapter assigned to RV
and then you are loading the list as
adapter.set(exampleList) // This adapter is not associated with the RV
to fix this change the above lines in onActivityCreated to
adapter = ExampleAdapter()
recycler_view.adapter = adapter

Blank fragment is displayed

I am creating a food ordering app . I am fetching the list of restaurants using volley .
Error:
The restaurant list does not displayed and in the logcat window the following displayed:
E/RecyclerView: No adapter attached; skipping layout
What I have tried to resolve:
used postman to verify volley response,the response is as expected
made sure if the variables were received in the right order
made sure that the array was received in the right format.
I attach the code of the HomeFragment and the adapter file
HomeFragment.class
class HomeFragment : Fragment() {
lateinit var recyclerRestaurant: RecyclerView
lateinit var progressLayout: RelativeLayout
lateinit var progressBar: ProgressBar
lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var recyclerAdapter: RestaurantRecyclerAdapter
var restaurantList = arrayListOf<Restaurant>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
setHasOptionsMenu(true)
recyclerRestaurant = view.findViewById(R.id.recyclerRestaurant)
progressLayout = view.findViewById(R.id.progressLayout)
progressBar = view.findViewById(R.id.progressBar)
layoutManager = LinearLayoutManager(activity)
progressLayout.visibility= View.VISIBLE
val queue = Volley.newRequestQueue(activity as Context)
val url = "http://13.235.250.119/v2/restaurants/fetch_result/"
if (ConnectionManager().checkConnectivity(activity as Context)) {
val jsonObjectRequest = object : JsonObjectRequest(
Request.Method.GET,url , null,
Response.Listener<JSONObject>{
progressLayout.visibility = View.GONE
try {
val data = it.getJSONObject("data")
val success = data.getBoolean("success")
if (success) {
val data = it.getJSONObject("data").getJSONArray("data")
for(i in 0 until data.length()) {
val resObject = data.getJSONObject(i)
val restaurants = Restaurant(
resObject.getString("id").toInt(),
resObject.getString("name"),
resObject.getString("rating"),
resObject.getString("cost_per_person"),
resObject.getString("image_url")
)
restaurantList.add(restaurants)
if(activity != null) {
recyclerAdapter = RestaurantRecyclerAdapter(activity as Context, restaurantList)
val mLayoutManager=LinearLayoutManager(activity)
recyclerRestaurant.layoutManager =mLayoutManager
recyclerRestaurant.adapter = recyclerAdapter
recyclerRestaurant.setHasFixedSize(true)
}
}
}
else {
Toast.makeText(
activity as Context,
"some error has occurred",
Toast.LENGTH_SHORT
).show()
}
}catch (e: JSONException){
e.printStackTrace()
}
},
Response.ErrorListener {
if(activity != null){
Toast.makeText(activity as Context,"Volley error has occurred", Toast.LENGTH_LONG).show() }
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["Content-type"] = "application/json"
headers["token"] = "06f579db533924"
return headers
}
}
queue.add(jsonObjectRequest)
}else{
val dialog = AlertDialog.Builder(activity as Context)
dialog.setTitle("error")
dialog.setMessage("Internet connection not found")
dialog.setPositiveButton("open settings"){ text, listener->
val settingsIntent = Intent(Settings.ACTION_WIRELESS_SETTINGS)
startActivity(settingsIntent)
activity?.finish()
}
dialog.setNegativeButton("exit"){text,listener->
ActivityCompat.finishAffinity(activity as Activity)
}
dialog.create()
dialog.show()
}
return view
}
}
RestaurantRecyclerAdapter.class
class RestaurantRecyclerAdapter(val context:Context, val itemList: ArrayList<Restaurant> ):RecyclerView.Adapter<RestaurantRecyclerAdapter.RestaurantViewHolder>() {
class RestaurantViewHolder(view: View): RecyclerView.ViewHolder(view){
val txtRestaurantName :TextView= view.findViewById(R.id.txtRestaurantName)
val imgRestaurantImage :ImageView = view.findViewById(R.id.imgRestaurantImage)
val txtRating : TextView = view.findViewById(R.id.txtRating)
val txtPerPerson : TextView = view.findViewById(R.id.txtPerPerson)
val llContent : LinearLayout = view.findViewById(R.id.llContent)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RestaurantViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_single_row,parent,false)
return RestaurantViewHolder(view)
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onBindViewHolder(holder: RestaurantViewHolder, position: Int) {
val restaurant = itemList[position]
holder.txtRestaurantName.text = restaurant.name
holder.txtRating.text = restaurant.rating
holder.txtPerPerson.text = restaurant.cost_per_person
Picasso.get().load(restaurant.image).error(R.drawable.ic_food).into(holder.imgRestaurantImage)

Can we retrieve firebase data into spinner?

I have added firebase database and the data also gets saved into the firebase realtime database, but it doesnot gets shown into the spinner, my spinner is showing no value.If theres some other way?
This is the code of my fragment:
class IncomeFragment: Fragment(){
//FAB
lateinit var addBankFab: FloatingActionButton
lateinit var addBankText: TextView
//Spinner
lateinit var spinner: Spinner
lateinit var dropDown: TextView
//Firebase Database
lateinit var mAuth: FirebaseAuth
lateinit var mIncomeDatabase: DatabaseReference
lateinit var mBankDatabase: DatabaseReference
lateinit var helper: FirebaseHelper
//Recycler View
lateinit var recyclerView: RecyclerView
//TextView
lateinit var incomeTotal : TextView
//Update Edit Text
lateinit var editAmount: EditText
lateinit var editType: EditText
lateinit var editNote: EditText
lateinit var editBankName:EditText
//Button for update and delete
lateinit var btnUpdate: Button
lateinit var btnDelete: Button
lateinit var btnSave : Button
lateinit var btnCancel:Button
//Data item Value
lateinit var type: String
lateinit var note: String
var amount: Int = 0
lateinit var post_key:String
lateinit var name:String
lateinit var ac:String
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myview= inflater.inflate(R.layout.fragment_income, container, false)
mAuth= FirebaseAuth.getInstance()
val mUser = mAuth.currentUser
val uid = mUser?.uid
addBankFab=myview.findViewById(R.id.add_bank_fab)
addBankText=myview.findViewById(R.id.add_bank_text)
spinner=myview.findViewById(R.id.incomeSpinner)
mIncomeDatabase =
FirebaseDatabase.getInstance().reference.child("IncomeData").child(uid.toString())
incomeTotal=myview.findViewById(R.id.income_txt_result)
mBankDatabase= FirebaseDatabase.getInstance().reference.child("BankData").child(uid.toString())
helper = FirebaseHelper(mBankDatabase)
spinner.setAdapter(
activity?.let {
ArrayAdapter<String>(
it,
android.R.layout.simple_list_item_1,
helper.retrieve()
)
}
)
recyclerView=myview.findViewById(R.id.incomeRecyclerView)
val layoutManager = LinearLayoutManager(activity)
layoutManager.reverseLayout = true
layoutManager.stackFromEnd = true
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = layoutManager
mIncomeDatabase.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var totalvalue :Int = 0
for (ds in dataSnapshot.children) {
val data: Data = ds.getValue<Data>(Data::class.java)!!
totalvalue+=data.amount
val stTotalValue:String = valueOf(totalvalue)
incomeTotal.text = stTotalValue+".00"
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
return myview
}
private fun insertBank() {
val bankdialog = AlertDialog.Builder(activity)
val inflater = LayoutInflater.from(activity)
val view: View = inflater.inflate(R.layout.add_bank_layout, null)
bankdialog.setView(view)
val dialog = bankdialog.create()
dialog.setCancelable(false)
val BankName = view.findViewById<EditText>(R.id.account_bank)
val BankAc = view.findViewById<EditText>(R.id.account_number)
val btnSaveBank = view.findViewById<Button>(R.id.btn_save_bank)
val btnCancelBank = view.findViewById<Button>(R.id.btn_cancel_bank)
btnSaveBank.setOnClickListener {
val name = BankName.text.toString().trim()
val ac = BankAc.text.toString().trim()
if (TextUtils.isEmpty(name)) {
BankName.error = "Required Field..."
return#setOnClickListener
}
if (TextUtils.isEmpty(ac)) {
BankAc.error = "Required Field..."
return#setOnClickListener
}
val bankacno = ac.toInt()
val id: String? = mBankDatabase.push().key
val mDate: String = DateFormat.getDateInstance().format(Date())
val bankdata = EmiData(bankacno, name, id, mDate)
mBankDatabase.child(id.toString()).setValue(bankdata)
Toast.makeText(activity, "DATA ADDED", Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
btnCancelBank.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}
override
fun onStart() {
super.onStart()
val options = FirebaseRecyclerOptions.Builder<Data>()
.setQuery(mIncomeDatabase, Data::class.java)
.setLifecycleOwner(this)
.build()
val firebaseRecyclerAdapter: FirebaseRecyclerAdapter<Data, MyViewHolder> =
object : FirebaseRecyclerAdapter<Data, MyViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.income_recycler_data, parent, false)
)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int, model: Data) {
holder.setType(model.type)
holder.setAmount(model.amount)
holder.setDate(model.date)
holder.setNote(model.note)
holder.mView.setOnClickListener {
post_key= getRef(position).key.toString()
type=model.type
note=model.note
amount=model.amount
updateDataItem()
}
}
}
recyclerView.adapter = firebaseRecyclerAdapter
}
class MyViewHolder(itemView: View) : ViewHolder(itemView) {
val mView = itemView
fun setType(type: String) {
val mType = mView.findViewById<TextView>(R.id.type_txt_income)
mType.text = type
}
fun setNote(note: String) {
val mNote = mView.findViewById<TextView>(R.id.note_txt_income)
mNote.text = note
}
fun setDate(date: String) {
val mDate = mView.findViewById<TextView>(R.id.date_txt_income)
mDate.text = date
}
fun setAmount(amount: Int) {
val mAmount = mView.findViewById<TextView>(R.id.amount_txt_income)
val stAmount = valueOf(amount)
mAmount.text = stAmount
}
}
private fun updateDataItem() {
val mydialog = AlertDialog.Builder(activity)
val inflater = LayoutInflater.from(activity)
val myView: View = inflater.inflate(R.layout.update_data_item, null)
mydialog.setView(myView)
val dialog = mydialog.create()
val editAmount = myView.findViewById<EditText>(R.id.amount_edit)
val editType = myView.findViewById<EditText>(R.id.type_edit)
val editNote = myView.findViewById<EditText>(R.id.note_edit)
//Set data to edit text..
editType.setText(type)
editType.setSelection(type.length)
editNote.setText(note)
editNote.setSelection(note.length)
editAmount.setText(valueOf(amount))
editAmount.setSelection(valueOf(amount).length)
val btnUpdate = myView.findViewById<Button>(R.id.btn_update)
val btnDelete = myView.findViewById<Button>(R.id.btn_delete)
btnUpdate.setOnClickListener {
type = editType.text.toString().trim()
note = editNote.text.toString().trim()
var mdAmount = amount.toString()
mdAmount = editAmount.text.toString().trim { it <= ' ' }
val myAmount = mdAmount.toInt()
val mDate: String = DateFormat.getDateInstance().format(Date())
val data = Data(myAmount, type, note, post_key, mDate)
mIncomeDatabase.child(post_key).setValue(data)
dialog.dismiss()
}
btnDelete.setOnClickListener {
mIncomeDatabase.child(post_key).removeValue()
dialog.dismiss()
}
dialog.show()
}
}
This is my firebase helper:
class FirebaseHelper(val db: DatabaseReference) {
private var saved: Boolean? = null
//SAVE
fun save(bankData: BankData?): Boolean? {
saved = if (bankData == null) {
false
} else {
try {
db.child("name").push().setValue(bankData)
true
} catch (e: DatabaseException) {
e.printStackTrace()
false
}
}
return saved
}
//READ
fun retrieve(): ArrayList<String> {
val bankNames = ArrayList<String>()
db.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(
dataSnapshot: DataSnapshot,
s: String?
) {
fetchData(dataSnapshot, bankNames)
}
override fun onChildChanged(
dataSnapshot: DataSnapshot,
s: String?
) {
fetchData(dataSnapshot, bankNames)
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {}
override fun onChildMoved(
dataSnapshot: DataSnapshot,
s: String?
) {
}
override fun onCancelled(databaseError: DatabaseError) {}
})
return bankNames
}
private fun fetchData(
snapshot: DataSnapshot,
bankData: ArrayList<String>
) {
bankData.clear()
val name: BankData? = snapshot.getValue(BankData::class.java)
bankData.add(bankData.toString())
}
}
Your spinner shows no value because the data is not retrieved yet from the DB.
So what you should do is create a callback from FirebaseHelper to IncomeFragment
First, create a callback
interface FirebaseHelperCallback {
fun dataRetrievedFromDB(data: List<String>)
}
Second, create a variable, setter function and call dataRetrievedFromDB function in FirebaseHelper class
class FirebaseHelper(val db: DatabaseReference) {
private lateinit var firebaseHelperCallback: FirebaseHelperCallback
fun setFirebaseHelperCallback(firebaseHelperCallback: FirebaseHelperCallback) {
this.firebaseHelperCallback = firebaseHelperCallback
}
...
private fun fetchData(snapshot: DataSnapshot, bankData: ArrayList<String>) {
bankData.clear()
val name: BankData? = snapshot.getValue(BankData::class.java)
bankData.add(bankData.toString())
firebaseHelperCallback.dataRetrievedFromDB(bankData)
}
}
Lastly, implement the callback in IncomeFragment
class IncomeFragment: Fragment(), FirebaseHelperCallback {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
...
helper.setFirebaseHelperCallback(this)
}
...
override fun dataRetrievedFromDB(data: List<String>) {
spinner.setAdapter(
activity?.let {
ArrayAdapter<String>(
it,
android.R.layout.simple_list_item_1,
data
)
}
)
}
}

No Error in the Log but RecyclerView is not displaying any JSON value-No error in the code too---Volley

I am trying to display name and age from a JSON Array in a HomeFragment. I have model, data and UI package. I am not seeing any error in the code or log but I am not getting the output in my activity. I am getting the JSON output in my response log and Commented for loop is working in recyclerview but If I use the real JSON value then fragment is not displaying any values. Your help is appreciated.
Home Fragment.kt
class HomeFragment : Fragment() {
private var adapter:PersonListAdapter?=null
private var personList:ArrayList<Person>?=null
private var layoutManager: RecyclerView.LayoutManager?=null
var volleyRequest: RequestQueue?=null
val SchoolLink="https://www.abc.app/"
//JSON Output
//[{"name":"AAA","age":"20"},{"name":"BBBB","age":"30"}]
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
volleyRequest= Volley.newRequestQueue(this.context)
val view = inflater.inflate(R.layout.fragment_home, container, false)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
personList=ArrayList<Person>()
layoutManager= LinearLayoutManager(this.context)
adapter= PersonListAdapter(personList,this.context!!)
recyclerView.layoutManager=layoutManager
recyclerView.adapter=adapter
/*
for (i in 0..16) {
val person = Person()
person.name="Hello" + i
person.age = 20 + i
personList!!.add(person)
}*/
val jsonArray=JsonArrayRequest(Request.Method.GET,SchoolLink,
Response.Listener {
response: JSONArray ->
try {
Log.d("Response from JSON",response.toString())
for(i in 0..response.length()-1)
{
val person = Person()
val SchoolObj=response.getJSONObject(i)
var name=SchoolObj.getString("name")
person.name=name
Log.d("name from JSON",name)
var age:String=SchoolObj.getString("age")
person.age=age.toDouble()
Log.d("age from JSON",age)
personList!!.add(person)
}
adapter!!.notifyDataSetChanged()
} catch (e:JSONException){e.printStackTrace()}
},
Response.ErrorListener {
error ->
try {
Log.d("Error",error.toString())
}
catch (e: JSONException){e.printStackTrace()}
})
volleyRequest!!.add(jsonArray)
return view
}
fun getJsonArray(Url:String)
{
}
}
PersonListAdapter.kt
class PersonListAdapter(private val list: ArrayList<Person>,
private val context: Context)
: RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
override fun getItemCount(): Int {
return list.size
}
override fun onCreateViewHolder(parent: ViewGroup?, position: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.bindItem(list[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItem(person: Person) {
var name: TextView = itemView.findViewById(R.id.name) as TextView
var age: TextView = itemView.findViewById(R.id.age) as TextView
name.text = person.name
age.text = person.age.toString()
itemView.setOnClickListener {
Toast.makeText(context, name.text, Toast.LENGTH_LONG ).show()
}
}
}
}
In this part:
for(i in 0..response.length()-1)
{
val SchoolObj=response.getJSONObject(i)
var name=SchoolObj.getString("name")
person.name=name
Log.d("name from JSON",name)
var age:String=SchoolObj.getString("age")
person.age=age.toDouble()
Log.d("age from JSON",age)
}
You does not add the person object in the person list.
for(i in 0..response.length()-1)
{
val person = Person()
val SchoolObj=response.getJSONObject(i)
var name=SchoolObj.getString("name")
person.name=name
Log.d("name from JSON",name)
var age:String=SchoolObj.getString("age")
person.age=age.toDouble()
Log.d("age from JSON",age)
personList!!.add(person)
}
adapter!!.notifyDataSetChanged()
Hope this will help for you.

Categories

Resources