This is the main activity:
class MainActivity : AppCompatActivity() {
private lateinit var newsRecyclerView: RecyclerView
private lateinit var progressBar: ProgressBar
private lateinit var newsArray:ArrayList<News>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
newsRecyclerView =findViewById(R.id.newsRecycler)
newsRecyclerView.layoutManager = LinearLayoutManager(this)
newsRecyclerView.hasFixedSize()
newsArray = ArrayList()
fetchData()
val adapter = NewsAdapter(newsArray)
newsRecyclerView.adapter = adapter
}
private fun fetchData() {
val url ="https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=ed1c2752375543da9dc2d9cf85cd1895"
val queue =Volley.newRequestQueue(this)
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET,
url,null,
Response.Listener{
val newsJSonArray =it.getJSONArray("articles")
for(i in 0 until newsJSonArray.length()) {
val newsJsonObject = newsJSonArray.getJSONObject(i)
val news = News(
newsJsonObject.getString("title"),
newsJsonObject.getString("url")
)
newsArray.add(news)
}
},Response.ErrorListener {
}
)
queue.add(jsonObjectRequest)
}
}
Adapter for RecyclerView:
class NewsAdapter(private val newsList: ArrayList<News>) :
RecyclerView.Adapter<NewsAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView =LayoutInflater.from(parent.context).inflate(R.layout.items,parent,false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val current = newsList[position]
holder.NewsHeading.text =current.Heading
holder.NewsDetail.text = current.NewsDetail
}
override fun getItemCount(): Int {
return newsList.size
}
class ViewHolder(itemView :View):RecyclerView.ViewHolder(itemView) {
var NewsHeading : TextView = itemView.findViewById(R.id.tvHeading)
var NewsDetail : TextView = itemView.findViewById(R.id.tvNews)
}
}
Data class:
data class News (
var Heading :String? = null,
var NewsDetail :String? = null
)
This is the error:- NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=ed1c2752375543da9dc2d9cf85cd1895
...........................................................
..........................................................
Related
So i am trying 2 things here and it seems to be all right but i am not beeing able to reach my API response. First i want to Filter my API to All information, only Images and only Pdf.- and second to make a recyclerView OnItemClickListener. If you can help to provide me this error i will very graceful. Thank You .
//Main Activity
class MainActivity : AppCompatActivity() {
private lateinit var recyclerview_users: RecyclerView
private lateinit var imageList : ArrayList<ImageModel>
private lateinit var imageAdapter: ImageAdapter
private var imageModel: List<ImageModel> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val allButton = findViewById<Button>(R.id.button_all)
allButton.setOnClickListener {
getBlob()
}
val photoButton = findViewById<Button>(R.id.button_image)
photoButton.setOnClickListener {
filterImageModel("photo")
}
val pdfButton = findViewById<Button>(R.id.button_pdf)
pdfButton.setOnClickListener {
filterImageModel("pdf")
}
recyclerview_users = findViewById(R.id.recycler_view)
recyclerview_users.setHasFixedSize(true)
recyclerview_users.layoutManager = LinearLayoutManager(this)
imageList = ArrayList()
imageAdapter = ImageAdapter(imageModel)
recyclerview_users.adapter = imageAdapter
var layoutManager = GridLayoutManager(this, 3)
recyclerview_users.layoutManager = layoutManager
getBlob()
}
private fun getBlob(){
val plcApi = ServiceGenerator.buildService(PLCApi::class.java)
val call = plcApi.getBlob()
call.enqueue(object : Callback<MutableList<ImageModel>>{
override fun onResponse(
call: Call<MutableList<ImageModel>>,
response: Response<MutableList<ImageModel>>
){
if (response.isSuccessful){
imageModel = response.body()!!
imageAdapter.updateImageModel(imageModel)
val imageList = response.body()!! as ArrayList<ImageModel>
val imageAdapter = ImageAdapter(imageList)
recyclerview_users.adapter = imageAdapter
imageAdapter.setOnitemClickListener { imageModel ->
val intent = Intent(this#MainActivity, ImageInformation::class.java)
startActivity(intent)
}
}else{
Toast.makeText(this#MainActivity, "Failed to retrieve data, please try again", Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<MutableList<ImageModel>>, t: Throwable){
Toast.makeText(this#MainActivity, "Network error, please check your connection", Toast.LENGTH_SHORT).show()
}
})
}
private fun filterImageModel(contentType: String) {
val filteredImageModel = imageModel.filter {
it.contentType == contentType
}
imageModel = filteredImageModel
imageAdapter.updateImageModel(filteredImageModel)
}
}
//ImageAdapter
class ImageAdapter(private var imageModel: List<ImageModel>) : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {
private var onItemClickListener: ((ImageModel) -> Unit)? = null
fun setOnitemClickListener(listener: (ImageModel) -> Unit){
onItemClickListener = listener
}
fun updateImageModel(newImageModel: List<ImageModel>){
imageModel = newImageModel
notifyDataSetChanged()
}
class ImageViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var downloadUrl: TextView = itemView.findViewById(R.id.downloadUrl)
var previewUrl: ImageView = itemView.findViewById(R.id.previewUrl)
var id: TextView = itemView.findViewById(R.id.id)
var filename: TextView = itemView.findViewById(R.id.fileName)
var filesize: TextView = itemView.findViewById(R.id.filesize)
var contentType: TextView = itemView.findViewById(R.id.contentType)
var createdBy: TextView = itemView.findViewById(R.id.createdBy)
var createdTimestamp: TextView = itemView.findViewById(R.id.createdTimestamp)
var creationSource: TextView = itemView.findViewById(R.id.creationSource)
var domainIdentityType: TextView = itemView.findViewById(R.id.domainIdentityType)
var domainIdentityValue: TextView = itemView.findViewById(R.id.domainIdentityValue)
var tags: TextView = itemView.findViewById(R.id.tags)
var description: TextView = itemView.findViewById(R.id.description)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_items, parent, false)
return ImageViewHolder(view)
}
#SuppressLint("CheckResult", "ResourceType")
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
val imageId = imageModel[position]
holder.downloadUrl.text = imageId.downloadUrl
if (imageId.contentType!!.startsWith("image")){
Glide.with(holder.itemView.context).load(imageId.previewUrl).into(holder.previewUrl)
}else{
holder.previewUrl.setImageResource(R.drawable.pdf)
}
holder.id.text = imageId.id
holder.filename.text = imageId.fileName
holder.filesize.text = imageId.fileName.toString()
holder.contentType.text = imageId.contentType
holder.createdBy.text = imageId.createdBy
holder.createdTimestamp.text = imageId.createdTimestamp
holder.creationSource.text = imageId.creationSource
holder.domainIdentityType.text = imageId.domainIdentityType
holder.domainIdentityValue.text = imageId.domainIdentityValue
holder.tags.text = imageId.tags.toString()
holder.description.text = imageId.description
holder.itemView.setOnClickListener{
onItemClickListener?.invoke(imageId)
}
}
override fun getItemCount(): Int {
return imageModel.size
}
}
//ImageModel
data class ImageModel(
#SerializedName("downloadUrl")
var downloadUrl: String? = null,
#SerializedName("previewUrl")
val previewUrl: String? = null,
#SerializedName("id")
var id: String? = null,
#SerializedName("fileName")
val fileName: String? = null,
#SerializedName("filesize")
val filesize: Int,
#SerializedName("contentType")
val contentType: String? = null,
#SerializedName("createdBy")
val createdBy: String? = null,
#SerializedName("createdTimestamp")
val createdTimestamp: String? = null,
#SerializedName("creationSource")
val creationSource: String? = null,
#SerializedName("domainIdentityType")
val domainIdentityType: String? = null,
#SerializedName("domainIdentityValue")
val domainIdentityValue: String? = null,
#SerializedName("tags")
val tags: List<String>? = null,
#SerializedName("description")
val description: String? = null)
: Parcelable{
constructor(parcel: Parcel) : this(
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readInt(),
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.createStringArrayList(),
parcel.readString()!!
)
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(downloadUrl)
parcel.writeString(previewUrl)
parcel.writeString(id)
parcel.writeString(fileName)
parcel.writeInt(filesize)
parcel.writeString(contentType)
parcel.writeString(createdBy)
parcel.writeString(createdTimestamp)
parcel.writeString(creationSource)
parcel.writeString(domainIdentityType)
parcel.writeString(domainIdentityValue)
parcel.writeString(tags.toString())
parcel.writeString(description)
}
companion object CREATOR : Parcelable.Creator<ImageModel> {
override fun createFromParcel(parcel: Parcel): ImageModel {
return ImageModel(parcel)
}
override fun newArray(size: Int): Array<ImageModel?> {
return arrayOfNulls(size)
}
}
}
//PLC API
interface PLCApi {
#GET("/BlobStorage/Blobs?StorageContainerId=ccef4ed7-7ec7-421d-8afb-3dce0a8be39c")
fun getBlob():Call<MutableList<ImageModel>>
}
//ServiceGenerator
object ServiceGenerator {
private val client = OkHttpClient.Builder().build()
private val retrofit = Retrofit.Builder()
.baseUrl("http://app-bbg-blob-assessment.azurewebsites.net/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun <T> buildService(service: Class<T>): T {
return retrofit.create(service)
}
}
//ImageInformation where i want to invoke the ClickListener
class ImageInformation : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_information)
val image = intent.getParcelableExtra<ImageModel>("ImageModel")
if (image != null){
val downloadUrl: TextView = findViewById(R.id.downloadUrla)
val previewUrl : ImageView = findViewById(R.id.previewUrla)
val id: TextView = findViewById(R.id.idsa)
val filename: TextView = findViewById(R.id.fileNamea)
val filesize: TextView = findViewById(R.id.filesizea)
val contentType: TextView = findViewById(R.id.contentTypea)
val createdBy: TextView = findViewById(R.id.createdBya)
val createdTimestamp: TextView = findViewById(R.id.createdTimestampa)
val creationSource: TextView = findViewById(R.id.creationSourcea)
val domainIdentityType: TextView = findViewById(R.id.domainIdentityTypea)
val domainIdentityValue: TextView = findViewById(R.id.domainIdentityValuea)
val tags: TextView = findViewById(R.id.tagsa)
val description: TextView = findViewById(R.id.descriptiona)
downloadUrl.text = image.downloadUrl
Glide.with(this).load(image.previewUrl).into(previewUrl)
id.text = image.id
filename.text = image.fileName
filesize.text = image.filesize.toString()
contentType.text = image.contentType
createdBy.text = image.createdBy
createdTimestamp.text = image.createdTimestamp
creationSource.text = image.creationSource
domainIdentityType.text = image.domainIdentityType
domainIdentityValue.text = image.domainIdentityValue
tags.text = image.tags.toString()
description.text = image.description
image.downloadUrl = downloadUrl.text as String?
image.id = id.text as String?
}
}
}
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
}
}
Somehow I see in the app messages I sent, but can't see those which should be received from others. Also when I'm sending a message it's sent to all users. Here I'm sending two classes, adapter and main chat activity. I tried using inner classes, different types of getItemViewType functions but nothing works.
MessageAdapter
class MessageAdapter(val context: Context, val messageList: ArrayList<Message>):
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val ITEM_RECIEVE = 1
val ITEM_SENT = 2
class SentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
{
val sentMessage = itemView.findViewById<TextView>(R.id.txt_sent_message)
}
class RecieveViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
{
val recieveMessage = itemView.findViewById<TextView>(R.id.txt_recieve_message)
}
override fun getItemViewType(position: Int): Int {
val currentMessage = messageList[position]
if (FirebaseAuth.getInstance().currentUser?.uid.equals(currentMessage.senderId)) {
return ITEM_SENT
}
else {
return ITEM_RECIEVE
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == 1)
{
val view = LayoutInflater.from(context).inflate(R.layout.recieve, parent, false)
Log.d("tag2", "testrecieveviewholderview11")
return RecieveViewHolder(view)
}
else
{
val view = LayoutInflater.from(context).inflate(R.layout.sent, parent, false)
Log.d("tag", "testsentviewholderview22")
return SentViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val currentMessage = messageList[position]
if(holder.javaClass == SentViewHolder::class.java)
{
val viewHolder = holder as SentViewHolder
holder.sentMessage.text = currentMessage.message
}
else
{
val viewHolder = holder as RecieveViewHolder
holder.recieveMessage.text = currentMessage.message
}
}
override fun getItemCount(): Int {
return messageList.size
}
}
And ChatActivity
var firebaseUser: FirebaseUser? = null
private lateinit var messageRecyclerView: RecyclerView
private lateinit var messageBox: EditText
private lateinit var sendButton: ImageButton
private lateinit var messageAdapter: MessageAdapter
private lateinit var messageList: ArrayList<Message>
private lateinit var mRef: DatabaseReference
var recieverRoom: String? = null
var senderRoom: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
val intent = Intent()
val name = intent.getStringExtra("name")
val recieverUid = intent.getStringExtra("uid")
val senderUid = FirebaseAuth.getInstance().currentUser?.uid
mRef = FirebaseDatabase.getInstance().reference
senderRoom = recieverUid + senderUid
recieverRoom = senderUid + recieverUid
messageRecyclerView = findViewById(R.id.RecyclerViewChat)
messageBox = findViewById(R.id.messageBox)
sendButton = findViewById(R.id.sendButton)
messageList = ArrayList()
messageAdapter = MessageAdapter(this, messageList)
messageRecyclerView.layoutManager = LinearLayoutManager(this)
messageRecyclerView.scrollToPosition(messageAdapter.itemCount-1)
messageRecyclerView.adapter = messageAdapter
mRef.child("chats").child(senderRoom!!).child("messages")
.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
messageList.clear()
for (postSnapshot in snapshot.children)
{
val message = postSnapshot.getValue(Message::class.java)
messageList.add(message!!)
}
messageAdapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
sendButton.setOnClickListener {
if (messageBox.text.toString().isEmpty() || messageBox.text.toString().isBlank())
{
messageBox.setText("")
}
else {
val message = messageBox.text.toString()
val messageObject = Message(message, senderUid)
mRef.child("chats").child(senderRoom!!).child("messages").push()
.setValue(messageObject).addOnSuccessListener {
mRef.child("chats").child(recieverRoom!!).child("messages").push()
.setValue(messageObject)
}
messageBox.setText("")
}
}
}
}
The error coming in this code is "Unresolved reference: message" and "Unresolved reference: senderId" in MessageAdapter. MessageAdapter is not able to take variables that are declared in Message class(message and senderId).
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)
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.