Here is my main class where I'm adding JASON data in ArrayList using volley.
Toast show the JASON data but array does not show any data. I'm trying to solve my error from last 3 days.
I also read many questions on stack but i have no solution for this please help me
var item = ArrayList<dumy_item_list>()
var url = "https://apps.faizeqamar.website/charity/api/organizations"
var rq: RequestQueue = Volley.newRequestQueue(this)
var sr = StringRequest(Request.Method.GET, url, Response.Listener { response ->
var jsonResponse = JSONObject(response)
var jsonArray: JSONArray = jsonResponse.getJSONArray("data")
for (i in 0..jsonArray.length() - 1) {
var jsonObject: JSONObject = jsonArray.getJSONObject(i)
var name = jsonObject.getString("name")
val data = dumy_item_list()
data.setName(jsonObject.getString(name))
item.add(data)
Toast.makeText(applicationContext, "NGO Name is : $name", Toast.LENGTH_LONG).show()
}
},
Response.ErrorListener { error ->
Toast.makeText(applicationContext, error.message, Toast.LENGTH_LONG).show()
})
rq.add(sr)
var away_recycler = findViewById<RecyclerView>(R.id.away_recycler)
var adaptor = custom_adopter(item, applicationContext)
away_recycler.layoutManager = GridLayoutManager(applicationContext, 1)
away_recycler.adapter = adaptor
}
Here is my adapter class where I'm using getName() function
class custom_adopter(data: ArrayList<dumy_item_list>, var context: Context) :
RecyclerView.Adapter<custom_adopter.viewHolder>() {
var data: List<dumy_item_list>
init {
this.data = data
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): custom_adopter.viewHolder {
var layout = LayoutInflater.from(context).inflate(R.layout.dumy_item, parent, false)
return viewHolder(layout)
}
override fun onBindViewHolder(holder: custom_adopter.viewHolder, position: Int) {
holder.tv_dummy_name_donnor.text = data[position].getName()
holder.card.setOnClickListener {
var intent = Intent(context, ngosProfile::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(context, intent, null)
}
}
override fun getItemCount(): Int {
return data.size
}
class viewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal var tv_dummy_name_donnor: TextView
internal var card: CardView
init {
tv_dummy_name_donnor = itemView.findViewById(R.id.tv_dummy_name_donnor)
card = itemView.findViewById(R.id.card)
}
}
}
follow this code this work for me. (var adaptor = custom_adopter(item, applicationContext) away_recycler.adapter = adaptor progressBar2?.visibility = View.INVISIBLE ) singe the value to adaptor after the loop.
class MainActivity : AppCompatActivity() {
var progressBar2:ProgressBar?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var item = ArrayList<dumy_item_list>()
var progressBar2 = findViewById<ProgressBar>(R.id.progressBar2)
var away_recycler = findViewById<RecyclerView>(R.id.away_recycler)
away_recycler.layoutManager = GridLayoutManager(applicationContext, 1)
var url = "https://apps.faizeqamar.website/charity/api/organizations"
var rq: RequestQueue = Volley.newRequestQueue(this)
var sr = StringRequest(Request.Method.GET, url, Response.Listener { response ->
var jsonResponse = JSONObject(response)
var jsonArray: JSONArray = jsonResponse.getJSONArray("data")
for (i in 0..jsonArray.length() - 1) {
var jsonObject: JSONObject = jsonArray.getJSONObject(i)
var name = jsonObject.getString("ngo_name")
var about = jsonObject.getString("ngo_desc")
item.add(dumy_item_list(name,about))
}
var adaptor = custom_adopter(item, applicationContext)
away_recycler.adapter = adaptor
progressBar2?.visibility = View.INVISIBLE
},
Response.ErrorListener { error ->
})
rq.add(sr)
}
I guess you have the RecyclerView with all items, but they are empty
so the issue should be where you fill the list of you adapter..in this below line exactly :
data.setName(jsonObject.getString(name))
it must be something like
data.setName(name)
OR
data.setName(jsonObject.getString("name"))
You should call method notifyDataSetChanged of the adapter after the data is loaded in your list in order to inform that there is new data.
Related
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
}
}
From the Android app, I wrote for I want to add, add a button in the toolbar that acts as a toggle. When the toggle is disabled (the default state) all posts should be shown, when it is enabled (after a tap) the list should only show the posts having user_id set to 1 and sorted by descending published_at. Tapping on the button again will return it to its default state.
Note that publishedAt returning date and publishedAt and user_id coming from postList from the server I want to know how can I implement above requirement what kind of steps should I have to follow
below my logic implementation in MainActivity.kt
class MainActivity : AppCompatActivity() {
#Inject
lateinit var restInterface: RestInterface
private fun initializeDagger() = App.appComponent.inject(this)
var context: Context? = null
private var filteredList: List<Post>? = null
private var recyclerView: RecyclerView? = null
private var switch1: Switch? = null
private var restAdapter: RestAdapter? = null
private var postList: List<Post>? = null
private var restList: RestList? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeDagger()
recyclerView = findViewById(R.id.recycler_view)
switch1 = findViewById(R.id.switch1)
fetchPosts()
switch1.setOnclickListener {
postList.forEach { postItem: Post ->
if (postItem.userId == 1)
filteredList.add(postItem)
}
recyclerView.post = filteredList
recyclerView.notifyDatasetChanged()
}
// Collections.sort( filteredList.get(4).publishedAt, Collections.reverseOrder());
}
private fun fetchPosts() {
val progress = ProgressDialog(this)
progress.setMessage("Loading... ")
progress.isIndeterminate = true
progress.show()
restInterface?.getPosts?.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableSingleObserver<Response<RestList>>() {
override fun onSuccess(response: Response<RestList>) {
restList = response.body()
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView?.layoutManager = layoutManager
// initialize postList with posts
postList = restList?.posts
restAdapter = postList?.let { RestAdapter(it, restList) }
recyclerView?.adapter = restAdapter
}
override fun onError(e: Throwable) {
progress.dismiss()
Toast.makeText(context, "" + e.message, Toast.LENGTH_SHORT).show()
}
})
}
}
below my RestAdapter.kt
class RestAdapter(val post: List<Post>,val restList: RestList?) : RecyclerView.Adapter<RestAdapter.PostHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.post_list, null)
return PostHolder(itemView)
}
override fun getItemCount(): Int {
return post.size
}
override fun onBindViewHolder(holder: PostHolder, position: Int) {
val posts = post[position]
Picasso
.get() // give it the context
.load(posts.image) // load the image
.into(holder.postImage)
holder.userId.text = posts.userId.toString()
holder.postTitle.text = posts.title
holder.postTime.text = posts.publishedAt
holder.postDescription.text = posts.description
}
class PostHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val postImage: ImageView = itemView.findViewById(R.id.postImage)
val userId: TextView = itemView.findViewById(R.id.userId)
val postTitle: TextView = itemView.findViewById(R.id.postTitle)
val postTime: TextView = itemView.findViewById(R.id.postTime)
val postDescription: TextView = itemView.findViewById(R.id.postDescription)
}
}
You can use method .sortedByDescending or .sortedBy on list :)
[Edit]
I give you a simple solution for that, maybe not the best but should work
1. Change RestAdapter constructor to (var post: List,val restList: RestList?)
Add method to updateData in apadapter:
fun filterData(isChecked: Boolean) {
if (isChecked) {
val filteredList = arrayListOf<Post>()
filteredList.addAll(restList?posts.filter { it.user_id == 1 }.sortedByDescending { it.published_at })
post = filteredList
} else {
post = restList?.posts
}
notifyDatasetChanged()
}
And in your class use this:
switch1.setOnclickListener {
restAdapter?.filterData(switch1.isChecked()//state of your switch i.e isChecked() which return true or false)
}
I am trying to open respective image of list item on other activity. I have listView already filled with JSON content but don't know how and where to set onItemClickListener on already filled listview? I tried, but getting no response on Itemclick. Would you please let me know how can I achieve it?
You can check my code below:
class MainActivity : AppCompatActivity() {
lateinit var listView : ListView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val editText = findViewById<EditText>(R.id.editText)
val url =editText.text
listView = findViewById<ListView>(R.id.listView)
var redColor =Color.parseColor("#FF0000")
listView.setBackgroundColor(redColor)
var load = findViewById<Button>(R.id.button)
load.setOnClickListener{
AsyncTaskHandler().execute(url.toString())
}
}
inner class AsyncTaskHandler:AsyncTask<String,String,String>() {
override fun onPreExecute() {
super.onPreExecute()
findViewById<ProgressBar>(R.id.loader).visibility = View.VISIBLE
}
override fun doInBackground(vararg p0: String?): String {
return try {
p0.first().let {
val url = URL(it)
val urlConnect = url.openConnection() as HttpURLConnection
urlConnect.connectTimeout = 700
publishProgress(100.toString())
urlConnect.inputStream.bufferedReader().readText()
}
} catch (e: Exception) {
p0.first().let {
val url = URL(it)
val urlConnect = url.openConnection() as HttpURLConnection
urlConnect.disconnect().toString()
}
}
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
findViewById<ProgressBar>(R.id.loader).visibility = View.GONE
jsonResult(result)
Log.d("Fetched Data", result)
}
private fun jsonResult(jsonString: String?){
val jsonArray = JSONArray(jsonString)
val list=ArrayList<MyData>()
var i = 0
while(i<jsonArray.length()){
val jsonObject=jsonArray.getJSONObject(i)
list.add(
MyData(
jsonObject.getString("author"),
jsonObject.getString("photo")
)
)
i++
}
val adapter = ListAdapter(this#MainActivity,list)
val listView = findViewById<ListView>(R.id.listView)
listView.adapter = adapter
listView.onItemClickListener = AdapterView.OnItemClickListener {
_, _, i, _ ->
Toast.makeText(this#MainActivity,
"you selected item " + (i + 1),
Toast.LENGTH_LONG).show()
}
}
}
}
Inside in your itemClickListener please add like this:
val otherIntent = Intent(this#MainActivity, OtherActivity::class.java)
otherIntent.putExtra("listItem, data)
startActivity(otherIntent)
And OtherActivity receive data like this:
var data = intent.getSerializableExtra("listItem") as MyData?
MyData should be serializable
class MyData(): Serializable
I am following this tutorial https://www.codexpedia.com/android/android-tablayout-with-many-tabs-kotlin/
i am modify method to add fragment, but i need jump to specific tab in tablayout. this tutorial not return the tab position (page) correctly and every jump (lets say tab 5), always load every tab (0,1,2,3,4,5) not straight to tab 5, every tab need to take data from server so its take to much time for fetching data in all tab.
Listing Class
class Listing : AppCompatActivity() {
// From server
var latitude = ""
var longitude = ""
var category:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_listing)
getCategory()
}
fun getCategory(){
val builder = AlertDialog.Builder(this)
val dialogView=layoutInflater.inflate(R.layout.progress_dialog,null)
builder.setView(dialogView)
builder.setCancelable(false)
val dialog = builder.create()
dialog.show()
var rq: RequestQueue = Volley.newRequestQueue(this)
var sr = object : StringRequest(Request.Method.POST, user_info.get_category, Response.Listener { response ->
//========================================================================================= data from server
Handler().postDelayed({dialog.dismiss()},0)
Log.i("AIM", response.toString())
val pageAdapter = MyPagerAdapter(supportFragmentManager)
var jsonObject = JSONObject(response)
var data:JSONObject = jsonObject["data"] as JSONObject
var jsonArray = data.getJSONArray("vendor_type")
for (i in 0 until jsonArray.length()) {
var jo = jsonArray.getJSONObject(i)
var id = jo["id"].toString()
var nama = jo["nama"].toString()
pageAdapter.add(FirstFragment.newInstance(i), nama)
user_info.nama_category.add(i,nama)
Log.d("aim","Fragment created")
}
viewpager_main.adapter = pageAdapter
tabs_main.setupWithViewPager(viewpager_main)
if (category != 0){
var fix = category - 1
viewpager_main.setCurrentItem(fix, false)
}
}, Response.ErrorListener { response ->
//========================================================================================= error handling
Handler().postDelayed({dialog.dismiss()},0)
var networkResponse = response.networkResponse
if (networkResponse == null){
Toast.makeText(this, "Tidak terhubung dengan server", Toast.LENGTH_LONG).show()
}
}) { }
sr.retryPolicy = DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
rq.add(sr)
}
}
Fragment
class FirstFragment : Fragment() {
private val vendorData = mutableListOf<vendor_model>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_first, container, false)
val page = getArguments()!!.getInt(PAGE_NUM)
Log.d("aim", "page : $page")
getVendor(page)
return view
}
companion object {
val PAGE_NUM = "PAGE_NUM"
fun newInstance(page: Int): FirstFragment {
val fragment = FirstFragment()
val args = Bundle()
args.putInt(PAGE_NUM, page)
fragment.setArguments(args)
return fragment
}
}
fun getVendor(page: Int) {
val builder = activity?.let { AlertDialog.Builder(it) }
val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)
builder?.setView(dialogView)
builder?.setCancelable(false)
val dialog = builder?.create()
dialog?.show()
var category = page + 1
Log.d("aim", "category : $category")
var rq: RequestQueue = Volley.newRequestQueue(activity)
var sr = object : StringRequest(Request.Method.POST, url, Response.Listener { response ->
Handler().postDelayed({dialog?.dismiss()},0)
Log.i("AIM", response.toString())
var jsonObject = JSONObject(response)
var jsonArray = jsonObject.getJSONArray("list")
for (i in 0 until jsonArray.length()) {
var jo = jsonArray.getJSONObject(i)
var jarak: String
if (jo.isNull("distance")) {
jarak = "Unknown"
}else jarak = jo["distance"].toString() + " Km"
var id = jo["id_vendor"].toString()
var nama = jo["nama"].toString()
//var jarak = jo["distance"].toString()
var rating = jo["rating"].toString()
var status = jo["is_open"].toString()
var img = jo["file_logo"].toString()
var category = jo["vendor_type"].toString()
val mItem = vendor_model(id, nama, "$jarak", rating, status, img, category)
vendorData.add(mItem)
}
// ============ recycler_nearme ============
recyclerView.layoutManager = LinearLayoutManager(activity, OrientationHelper.VERTICAL,false)
val vendorAdapter = vendor_adapter()
recyclerView.adapter = vendorAdapter
vendorAdapter.setList(vendorData)
vendorData.clear()
}, Response.ErrorListener { response ->
Handler().postDelayed({dialog?.dismiss()},0)
//========================================================================================= error handling
Toast.makeText(activity, response.toString(), Toast.LENGTH_LONG).show()
var networkResponse = response.networkResponse
if (networkResponse == null){
Toast.makeText(activity, "Tidak terhubung dengan server", Toast.LENGTH_LONG).show()
}
else {
var code = networkResponse.statusCode
var err = networkResponse.data
Toast.makeText(activity, "Error : $code", Toast.LENGTH_LONG).show()
Log.i("AIM", err.toString())
}
}) {
override fun getParams(): MutableMap<String,String> {
var map = HashMap<String, String>()
map.put("text" , "")
map.put("tags" , "")
map.put("take" , "10")
map.put("skip" , "0")
map.put("sort_by" , "asc")
map.put("language" , "[]")
map.put("type" , "")
map.put("category" , "[$category]")
map.put("grade" , "[]")
map.put("nearme" , "0")
map.put("distance" , "")
map.put("location" , "")
map.put("latitude" , "")
map.put("longitude" , "")
map.put("open_now" , "")
map.put("price_min" , "")
map.put("price_max" , "")
map.put("rating" , "")
map.put("rating_max" , "")
map.put("rating_min" , "")
map.put("ratings" , "[]")
map.put("subject" , "")
return map
}
}
sr.retryPolicy = DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
rq.add(sr)
Log.i("aim", sr.body.toString(Charset.defaultCharset()))
}
}
Adapter
class MyPagerAdapter(fm: FragmentManager): FragmentPagerAdapter(fm){
private val tabNames: ArrayList<String>
private val fragments: ArrayList<Fragment>
init {
tabNames = ArrayList()
fragments = ArrayList()
}
fun add(fragment: Fragment, title: String) {
tabNames.add(title)
fragments.add(fragment)
}
override fun getCount(): Int {
return fragments.size
}
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getPageTitle(position: Int): CharSequence {
return tabNames[position]
}
}
thank you for your answer, really apreciated
You can pass additional parameter (second one as false):
viewpager_main.setCurrentItem(4, false)
Set true to smoothly scroll to the new item,
Set false to do transition immediately
I am trying to display list using recycler view but I am getting null value. I have three classes Test, TestModel and TestListAdapter. Below is my Json Output. I am getting an error in one place.
val catObj = response.getJSONObject(i).
If I mention i as int then I am getting an error so, I need to enter i.toString() for string conversion. Even after converting the i to string, I am not getting the output and no error in the error log. I am using Volley and Kotlin in my code. Any help is appreciated.
Error:--Type Mismatch
val catObj = response.getJSONObject(i)
Json Output:
[{"id":"1","name":"AAAA"},{"id":"3","name":"BBBB"}]
Test Class:
class Test : AppCompatActivity() {
var volleyRequest:RequestQueue?=null
var TestList: ArrayList<TestModel>?=null
var adapter:TestListAdapter?=null
var layoutManager: RecyclerView.LayoutManager?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_Test)
var HelloLink="https://www.abc.app"
TestList= ArrayList<TestModel>()
volleyRequest = Volley.newRequestQueue(this)
getTest(HelloLink)
}
fun getTest(url: String) {
print("Url Value is:"+url)
val catRequest = JsonObjectRequest(Request.Method.GET,
url, Response.Listener {
response: JSONObject ->
try {
for (i in 0..response.length() - 1) {
val Test=TestModel()
val catObj = response.getJSONObject(i)
var name = catObj.getString("name")
Test.name = name
Log.d("Name Result==>>", name)
TestList!!.add(Test)
adapter = TestListAdapter(TestList!!, this)
layoutManager = LinearLayoutManager(this)
recyclerViewTest.layoutManager = layoutManager
recyclerViewTest.adapter = adapter
}
adapter!!.notifyDataSetChanged()
}catch (e: JSONException) { e.printStackTrace()}
},
Response.ErrorListener {
error: VolleyError? ->
try {
Log.d("Error:", error.toString())
}catch (e: JSONException){e.printStackTrace()}
})
volleyRequest!!.add(catRequest)
}
}
TestListAdapter Class
class TestListAdapter(private val list:ArrayList<TestModel>,
private val context: Context):RecyclerView.Adapter<TestListAdapter.ViewHolder>()
{
override fun getItemCount(): Int {
return list.size
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
val view
=LayoutInflater.from(context).inflate(R.layout.list_Test,p0,false)
return ViewHolder(view)
}
override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
p0?.bindItem(list[p1])
}
class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
fun bindItem(Test:TestModel)
{
var name:TextView=itemView.findViewById<TextView>(R.id.CatName)
name.text=Test.name
}
}
}
Model Class
class TestModel
{
var id:Int?=null
var name:String?=null
}
As I mentioned on my comment--I am not that familiar with the kotlin language, but the JSON example you posted:
[{"id":"1","name":"AAAA"},{"id":"3","name":"BBBB"}]
is actually an JSONArray not a JSONObject so I think the code you should look like this:
fun getTest(url: String) {
print("Url Value is:"+url)
val catRequest = JsonArrayRequest(Request.Method.GET,
url, Response.Listener {
response: JSONArray ->
try {
for (i in 0..response.length() - 1) {
val Test=TestModel()
val catObj = response.getJSONObject(i)
var name = catObj.getString("name")
Test.name = name
Log.d("Name Result==>>", name)
TestList!!.add(Test)
adapter = TestListAdapter(TestList!!, this)
layoutManager = LinearLayoutManager(this)
recyclerViewTest.layoutManager = layoutManager
recyclerViewTest.adapter = adapter
}
adapter!!.notifyDataSetChanged()
}catch (e: JSONException) { e.printStackTrace()}
},
Response.ErrorListener {
error: VolleyError? ->
try {
Log.d("Error:", error.toString())
}catch (e: JSONException){e.printStackTrace()}
})
volleyRequest!!.add(catRequest)
}
Notice that the JsonArrayRequest is in place of the JsonObjectRequest and the response is JSONArray instead of the JSONObject.
You have some issue when you add data to your adapter,
Update your adapter as below
class TestListAdapter( private val context: Context):RecyclerView.Adapter<TestListAdapter.ViewHolder>()
private val list = arrayListOf<TestModel>
public fun injectData(list : ArrayList<TestModel>){
this.list.addAll(list)
notifyDataSetChanged()
}
{
override fun getItemCount(): Int {
return list.size
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
val view
=LayoutInflater.from(context).inflate(R.layout.list_Test,p0,false)
return ViewHolder(view)
}
override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
p0?.bindItem(list[p1])
}
class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
fun bindItem(Test:TestModel)
{
var name:TextView=itemView.findViewById<TextView>(R.id.CatName)
name.text=Test.name
}
}
}
and in your TestClass:
adapter = TestListAdapter(this)
layoutManager = LinearLayoutManager(this)
recyclerViewTest.layoutManager = layoutManager
recyclerViewTest.adapter = adapter
try {
for (i in 0..response.length() - 1) {
val Test=TestModel()
val catObj = response.getJSONObject(i)
var name = catObj.getString("name")
Test.name = name
Log.d("Name Result==>>", name)
TestList!!.add(Test)
}
adapter.injectData(TestList);
}catch (e: JSONException) { e.printStackTrace()}
And the minor thing, please consider when using !!, you should check null before using
Example, Instead of
TestList!!.add(Test)
Try
TestList?.let {
it.add(Test)
}