Blank fragment is displayed - android

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)

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
}
}

how to connect to different apis on different button click

I have placed buttons on these 6 items now all I need is when a user clicks on a button it has to connect to a api fetch and display content ,similarly clicking on all other buttons should connect to respective api s.Now creating a new activity and new adapter for each is causing redundant code how to implement this properly please help me
home fragment
class Homefragment : Fragment() {
lateinit var buttondept:Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view= inflater.inflate(R.layout.fragment_homefragment, container, false)
buttondept=view.findViewById(R.id.btnDept)
buttondept.setOnClickListener {
val intent=Intent(context,descactivity::class.java)
intent.putExtra("option","department")
startActivity(intent)
}
return view
}
}
desc activity
class descactivity : AppCompatActivity() {
lateinit var recyclerDashBoard: RecyclerView
lateinit var layoutmanager: RecyclerView.LayoutManager
lateinit var recyclerAdapter:Horizontal_RecyclerView
lateinit var progressLayout: RelativeLayout
lateinit var progressBar: ProgressBar
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_descactivity)
val bookInfoList = arrayListOf<Book>()
recyclerDashBoard = findViewById(R.id.recyclerDashboard)
progressBar = findViewById(R.id.progressbar)
progressLayout = findViewById(R.id.progresslayout)
progressLayout.visibility = View.VISIBLE
val intent=getIntent()
val selectionOption= intent.getStringExtra("option")
val queue = Volley.newRequestQueue(this as Context)
val url = "http://13.235.250.119/v1/book/fetch_books/"
if (ConnectionManager().checkConnectivity(this as Context)) {
val jsonObjectRequest =
object : JsonObjectRequest(Method.GET, url, null, Response.Listener {
try {
progressLayout.visibility = View.GONE
val success = it.getBoolean("success")
if (success) {
val data = it.getJSONArray("data")
for (i in 0 until data.length()) {
val bookJSONObject = data.getJSONObject(i)
val bookobject = Book(
bookJSONObject.getString("book_id"),
bookJSONObject.getString("name"),
bookJSONObject.getString("author"),
bookJSONObject.getString("rating"),
bookJSONObject.getString("price"),
bookJSONObject.getString("image")
)
bookInfoList.add(bookobject)
layoutmanager = LinearLayoutManager(this)
recyclerAdapter =
Horizontal_RecyclerView(this as Context, bookInfoList)
recyclerDashBoard.adapter = recyclerAdapter
recyclerDashBoard.layoutManager = layoutmanager
}
} else {
Toast.makeText(
this as Context,
"some error occurred!!",
Toast.LENGTH_SHORT
).show()
}
} catch (e: JSONException) {
Toast.makeText(
this as Context,
"some unknown error occured!!",
Toast.LENGTH_SHORT
).show()
}
}, Response.ErrorListener {
Toast.makeText(
this as Context,
"volley error occured!!",
Toast.LENGTH_SHORT
).show()
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["content-type"] = "application/json"
headers["token"] = "a07daa7f3efb3b"
return headers
}
}
queue.add(jsonObjectRequest)
}
}
}

firebase data to recyclerview in fragment

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
}

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