RecyclerView is displaying Null Value but No Error in the log - android

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

Related

Recyclerview doesn't show, with message error No adapter attached; skipping layout

Ii trying to run the recyclerview, but list item didn't show, and error message is No adapter attached; skipping layout
There is no error with the code, but when try to run, recyclerview doesn't show. Here the main activity, I try to show recyclerview using Parsing Json
companion object {
private val TAG = MainActivity::class.java.simpleName
}
private lateinit var binding: ActivityMainBinding
// private lateinit var adapter: UserAdapter
private var listUser = ArrayList<DataUser>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.title = "Github User Search"
binding.rvUser.setHasFixedSize(true)
val layoutManager = LinearLayoutManager(this)
val itemDecoration = DividerItemDecoration(this, layoutManager.orientation)
binding.rvUser.addItemDecoration(itemDecoration)
searchUsername()
getDataUser()
}
fun searchUsername () {
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = binding.searchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.queryHint = resources.getString(R.string.search_hint)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String): Boolean {
if(query.isEmpty()){
return true
} else{
listUser.clear()
getSearchUsername(query)
}
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
return false
}
})
}
private fun getSearchUsername(username: String) {
binding.progressBar.visibility = View.VISIBLE
val client = AsyncHttpClient()
client.addHeader("Authorization", "token<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>")
client.addHeader("User-Agent", "request")
client.get(
"https://api.github.com/search/users?q=$username",
object : AsyncHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Array<out Header>,
responseBody: ByteArray
) {
binding.progressBar.visibility = View.VISIBLE
val result = String(responseBody)
Log.d(TAG, result)
try {
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val responseObject = jsonArray.getJSONObject(i)
val userName = responseObject.getString("login")
val id = responseObject.getString("id")
val avatar = responseObject.getString("avatar_url")
listUser.add(DataUser(
userName,
id.toInt(),
avatar
))
}
val adapter = UserAdapter(listUser)
binding.rvUser.adapter = adapter
} catch (e: Exception) {
Log.d(TAG, e.message.toString())
}
}
override fun onFailure(
statusCode: Int,
headers: Array<out Header>,
responseBody: ByteArray,
error: Throwable
) {
binding.progressBar.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error.message}"
}
Toast.makeText(
this#MainActivity, errorMessage, Toast
.LENGTH_SHORT
).show()
}
})
}
private fun getDataUser() {
binding.progressBar.visibility = View.VISIBLE
val client = AsyncHttpClient()
client.addHeader("Authorization", "token YOUR_GITHUB_API_TOKEN")
client.addHeader("User-Agent", "request")
val url = "https://api.github.com/users"
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?) {
binding.progressBar.visibility = View.INVISIBLE
val result = String(responseBody!!)
Log.d(TAG, result)
try {
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val username: String = jsonObject.getString("login")
getSearchUsername(username)
}
} catch (e: Exception) {
Toast.makeText(this#MainActivity, e.message, Toast.LENGTH_SHORT)
.show()
e.printStackTrace()
}
}
override fun onFailure(statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable?) {
binding.progressBar.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error?.message + " GIT"}"
}
Toast.makeText(this#MainActivity, errorMessage, Toast.LENGTH_LONG)
.show()
}
})
}
}
And here the adapter
class UserAdapter(private val listDataDetailUser: ArrayList<DataUser>) :
RecyclerView.Adapter<UserAdapter.ListViewHolder>() {
private lateinit var onItemClickCallback: OnItemClickCallback
fun setOnItemCLickCallback(onItemClickCallback: OnItemClickCallback) {
this.onItemClickCallback = onItemClickCallback
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ListViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_profile_list, viewGroup, false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val data = listDataDetailUser[position]
Glide.with(holder.itemView.context)
.load(data.avatar_url)
.into(holder.avatar)
holder.username.text = data.login
}
override fun getItemCount(): Int = listDataDetailUser.size
inner class ListViewHolder(view : View) : RecyclerView.ViewHolder(view) {
val avatar: CircleImageView = view.findViewById(R.id.img_profile)
val username: TextView = view.findViewById(R.id.tv_username)
}
interface OnItemClickCallback {
fun onItemClicked(data: DataUser)
}
}
What can I try to resolve this?
You have not added LayoutManager to your Recyclerview.
Try adding LinearLayoutManager which you have created for your ItemDecoration.
binding.rvUser.setLayoutManager(layoutManager);

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

Why does my RecyclerView shows the same value every iteration?

It shows the correct number of objects, but gives them all the same value.
Background:
I am following a tut to build a Slack-like app. I am using the recycler view to show the list of channels.
This is my adapter
class ChannelsAdapter(val context: Context, val channels: ArrayList<Channel>) :
RecyclerView.Adapter<ChannelsAdapter.Holder>() {
inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val singleChannel = itemView.findViewById<TextView>(R.id.single_channel)
fun bindText(textVar: String, context: Context) {
singleChannel.text = textVar
}
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bindText(channels[position].toString(), context)
}
override fun getItemCount(): Int {
return channels.count()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.channel_list_layout, parent, false)
return Holder(view)
}
}
This is the "channel" class:
class Channel(val name: String, val Description: String, val id: String) {
override fun toString(): String {
return ("#$name")
}
}
This is the variable the data that is being assigned to the RecyclerView, and the functions that pulls the data from the server and
object MessageService {
val channels = ArrayList<Channel>()
fun getChannels(context: Context, complete: (Boolean) -> Unit) {
val channelsRequest =
object : JsonArrayRequest(Method.GET, URL_GET_CHANNELS, null, Response.Listener { response ->
try {
for (x in 0 until (response.length())) {
val channel = response.getJSONObject(0)
val channelName = channel.getString("name")
val channelDescription = channel.getString("description")
val channelId = channel.getString("_id")
val newChannel = Channel(channelName, channelDescription, channelId)
this.channels.add(newChannel)
}
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC:" + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener {
Log.d("ERROR", "Could not retrieve channels")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("Authorization", "Bearer ${AuthService.authToken}")
return headers
}
}
Volley.newRequestQueue(context).add(channelsRequest)
}
}
This val gets its data from the server as a JsonArray.
Just change your onBindViewHolder like this
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bindText(channels[position], context)
}
And your bindText function like this
inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val singleChannel = itemView.findViewById<TextView>(R.id.single_channel)
fun bindText(data: Channel, context: Context) {
singleChannel.text = data.name
}
}
Check where you are initializing Chanel and passing in the channels list. Make sure each channel is initialized inside the loop that appends the Channel into the list. Happened to me a while back e.g
while(true) {
Channel myChanel= new Channel()
myChanel.name = "name"
channels.add(myChanel)
}
// Pass list into adapter. Convert to kotlin :)
My problem was in the loop pulling the information from the server, foolish mistake.
for (x in 0 until (response.length())) {
val channel = response.getJSONObject(0)
val channelName = channel.getString("name")
val channelDescription = channel.getString("description")
val channelId = channel.getString("_id")
I kept pulling object "0" instead of "x"

parse JSON object using retrofit in kotlin

I am trying to show json data using retrofit library in kotlin
This is my Json:
[
{
"login": "mojombo",
"id": 1,
},
{
"login": "defunkt",
"id": 2,
}
]
My Main activity
call.enqueue(object : Callback<UserResponse> {
override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
Log.e("list","list")
val countrylist = response.body()
for (size in response.body()) {
System.out.println(size.toString())
}
// var listOfMovies: List<UserResponse> = response.body()?.results!!
// myCustomAdapter = UserListAdapter(applicationContext, listOfMovies)
// recyclerView.setAdapter(myCustomAdapter)
progressBar.visibility = View.GONE
}
override fun onFailure(call: Call<UserResponse>?, t: Throwable?) {
progressBar.visibility = View.GONE
Log.e("list", t.toString())
}
})
This an app that I build in kotlin using retrofit and rxjava in the best way possible using a test API.
Model
data class Post( val userID:Int, val title:String, val body: String)
Retrofit Package
IMyApi interface
interface IMyApi {
#get:GET("posts")
val posts: Observable<List<Post>>
}
RetrofitClient Object class
object RetrofitClient {
val instance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
Adapter Package
PostAdapter class
class PostAdapter(private val context: Context, private val postList: List<Post>)
:RecyclerView.Adapter<PostViewHolder>()
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
PostViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.post_item, parent, false)
return PostViewHolder(itemView)
}
override fun getItemCount(): Int {
return postList.size
}
override fun onBindViewHolder(holder: PostViewHolder, position: Int)
{
holder.userId.text = postList[position].userID.toString()
holder.title.text = postList[position].title
holder.body.text = StringBuilder(postList[position].body.substring(0,20))
.append("...").toString()
}
}
PostViewHolder class
class PostViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
var userId = itemView.txtID
var title = itemView.txtTitle
var body = itemView.txtBody
}
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var jsonApi: IMyApi
private var compositeDisposable: CompositeDisposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Init api
val retrofit = RetrofitClient.instance
jsonApi = retrofit.create(IMyApi::class.java)
// View
recycler_posts.layoutManager = LinearLayoutManager(this)
recycler_posts.setHasFixedSize(true)
fetchData()
}
private fun fetchData() {
compositeDisposable.add(jsonApi.posts
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { posts->displayData(posts)})
}
private fun displayData(posts: List<Post>?) {
val adapter = PostAdapter(this, posts!!)
recycler_posts.adapter = adapter
}
}
Using this as displayed above should help you solve your issue hopefully. Also when in the code you come across "recycler_posts". This is a id to the recycler added in activity_main. If you need me to include that let me know
That's what we have on our app
object GetFAQsAPI {
private val LOG_TAG = GetFAQsAPI.javaClass.simpleName
interface ThisCallback {
fun onSuccess(getFAQs: GetFAQs)
fun onFailure(failureMessage: String)
fun onError(errorMessage: String)
}
/* POST */
fun postData(jo: JsonObject, callback: GetFAQsAPI.ThisCallback) {
val call = Service.getService().get_faqs(jo)
call.enqueue(object : Callback<JsonObject> {
override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
//Log.e(LOG_TAG, response.body().toString());
try {
if (response.body()?.get("success")!!.asBoolean) {
val gson = GsonBuilder().setPrettyPrinting().create()
val getFAQs = gson.fromJson(response.body(), GetFAQs::class.java)
callback.onSuccess(getFAQs)
} else {
Log.e(LOG_TAG, "else")
val error = response.body()!!.get("err").asString
callback.onError(error)
}
} catch (e: Exception) {
Log.e(LOG_TAG, "exception" + e.localizedMessage)
callback.onFailure(e.message!!)
}
}
override fun onFailure(call: Call<JsonObject>, t: Throwable) {
Log.e(LOG_TAG, "onFailure: " + t.message)
callback.onFailure(t.message!!)
}
})
}
}
That's how we call it from our fragment - getFAQs is the object parsed.
private fun getFAQsAPI() {
showLoading(true)
val jo = JsonObject().apply {
addProperty("faq_category", "admin")
}
GetFAQsAPI.postData(jo, object : GetFAQsAPI.ThisCallback {
override fun onSuccess(getFAQs: GetFAQs) {
Log.i(LOG_TAG, "onSuccess")
showLoading(false)
updateUI(getFAQs)
}
override fun onFailure(failureMessage: String) {
Log.e(LOG_TAG, failureMessage)
}
override fun onError(errorMessage: String) {
Log.e(LOG_TAG, errorMessage)
}
})
}
Hope that helps.

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