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
}
}
Related
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
...........................................................
..........................................................
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?
}
}
}
When I use my Original Device where I'll upload Text and Images to the Firebase
and When I View it I can See the Images, but when I use Different Device I can see the Text but not the uploaded Image instead I can seethe Iclauncher, but the Image is still on Realtime Database as well as on Storage. I think my problem is if I use another device the Images from Firebase is not Loading or Downloading and I don't know what to do
This Is My Code
DetailsActivity.kt
class DetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
val intss = intent
var nameT = intss.getStringExtra("NAMET")
var locaT = intss.getStringExtra("LOCAT")
var imgT = intss.getStringExtra("IMGURI")
var desT = intss.getStringExtra("DEST")
var serT = intss.getStringExtra("SERT")
var acoT = intss.getStringExtra("ACOT")
var conT = intss.getStringExtra("CONT")
nameDetailTextView.text = nameT
locationDetailTextView.text = locaT
descriptionDetailTextView.text = desT
servicesDetailTextView.text = serT
accommodationDetailTextView.text = acoT
contactDetailTextView.text = conT
hotelDetailImageView.loadImage(imgT)
}
}
ItemsActivity.kt
class ItemsActivity : AppCompatActivity() {
private var mStorage:FirebaseStorage? = null
private var mDatabaseRef:DatabaseReference? = null
private var mDBListener:ValueEventListener? = null
private lateinit var mHotels:MutableList<HotelandInns>
private lateinit var listAdapter: ListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_items)
/**set adapter*/
mRecyclerView.setHasFixedSize(true)
mRecyclerView.layoutManager = LinearLayoutManager(this#ItemsActivity)
myDataLoaderProgressBar.visibility = View.VISIBLE
mHotels = ArrayList()
listAdapter = ListAdapter(this#ItemsActivity,mHotels)
mRecyclerView.adapter = listAdapter
/**set Firebase Database*/
mStorage = FirebaseStorage.getInstance()
mDatabaseRef = FirebaseDatabase.getInstance().getReference("hotels_uploads")
mDBListener = mDatabaseRef!!.addValueEventListener(object : ValueEventListener{
override fun onCancelled(error: DatabaseError) {
Toast.makeText(this#ItemsActivity,error.message, Toast.LENGTH_SHORT).show()
myDataLoaderProgressBar.visibility = View.INVISIBLE
}
override fun onDataChange(snapshot: DataSnapshot) {
mHotels.clear()
for (teacherSnapshot in snapshot.children){
val upload = teacherSnapshot.getValue(HotelandInns::class.java)
upload!!.key = teacherSnapshot.key
mHotels.add(upload)
}
listAdapter.notifyDataSetChanged()
myDataLoaderProgressBar.visibility = View.GONE
}
})
}
override fun onDestroy() {
super.onDestroy()
mDatabaseRef!!.removeEventListener(mDBListener!!)
}
}
ListAdapter.kt
class ListAdapter (var mContext:Context,var hotelsList:List<HotelandInns>):
RecyclerView.Adapter<ListAdapter.ListViewHolder>()
{
inner class ListViewHolder(var v:View): RecyclerView.ViewHolder(v){
var imgT = v.findViewById<ImageView>(R.id.hotelImageView)
var nameT = v.findViewById<TextView>(R.id.nameTextView)
var locaT = v.findViewById<TextView>(R.id.locationTextView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
var infalter = LayoutInflater.from(parent.context)
var v = infalter.inflate(R.layout.row_item,parent,false)
return ListViewHolder(v)
}
override fun getItemCount(): Int =hotelsList.size
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
var newList = hotelsList[position]
holder.nameT.text = newList.name
holder.locaT.text = newList.location
holder.imgT.loadImage(newList.imageUrl)
holder.v.setOnClickListener {
val desT = newList.description
val name = newList.name
val serT = newList.services
val acoT = newList.accommodation
val locat = newList.location
val imgUri = newList.imageUrl
val conT = newList.contact
val mIntent = Intent(mContext, DetailsActivity::class.java)
mIntent.putExtra("NAMET",name)
mIntent.putExtra("DEST",desT)
mIntent.putExtra("ACOT",acoT)
mIntent.putExtra("SERT",serT)
mIntent.putExtra("LOCAT",locat)
mIntent.putExtra("CONT", conT)
mIntent.putExtra("IMGURI",imgUri)
mContext.startActivity(mIntent)
}
}
}
Uitel.kt
fun ImageView.loadImage(url: String?){
val option = RequestOptions().placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
Glide.with(context)
.setDefaultRequestOptions(option)
.load(url)
.into(this)
}
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 trying to parse website using Jsoup. When I run the app, the parsed items come to console, I mean with println statements, but the list of items doesn't come to recyclerview of the fragment, just a blank screen appears. The code part is long, I am pasting the whole fragment(with recyclerview) and adapter codes here. Any help is appreciated.
Adapter Class:
class ExampleAdapter : RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>() {
// ExampleAdapter(private val exampleList: List<Books>)
private val exampleList = mutableListOf<Books>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.example_item, parent, false)
return ExampleViewHolder(itemView)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
// val currentItem = exampleList[position]
// holder.imageView.setImageResource(currentItem.imageResource)
// holder.textView1.text = currentItem.title
// holder.textView2.text = currentItem.description
// holder.textView3.text = currentItem.additionalInfo
holder.bind(exampleList[position])
}
override fun getItemCount(): Int = exampleList.size
class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView: ImageView = itemView.row_img
val textView1: TextView = itemView.row_tv_title
val textView2: TextView = itemView.row_tv_description
val textView3: TextView = itemView.row_tv_additional_info
fun bind(books: Books) {
textView1.text = books.title
textView2.text = books.description
Picasso.with(itemView.context)
.load(books.imageResource)
.transform(CropSquareTransformation())
.into(imageView)
textView3.text = books.additionalInfo
// link = books.linkDetails
}
}
//exampleList class içindeki val değerlerini silmeyince unresolved reference hatası veriyor:
fun set(list: MutableList<Books>) {
this.exampleList.clear()
this.exampleList.addAll(list)
notifyDataSetChanged()
}
}
class CropSquareTransformation : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = Math.min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val result = Bitmap.createBitmap(source, x, y, size, size)
if (result != source) {
source.recycle()
}
return result
}
override fun key(): String {
return "square()"
}
Fragment Class:
class ListBooksFragment : Fragment() {
private lateinit var adapter: ExampleAdapter
private val url ="https://openlibrary.org/search?q=men&mode=everything"
private val exampleList = mutableListOf<Books>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
recycler_view.layoutManager = LinearLayoutManager(this.context)
adapter = ExampleAdapter()
recycler_view.adapter = ExampleAdapter()
GlobalScope.launch {
getData()
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list_books, container, false)
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
ListBooksFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
private fun getData(){
val list = ArrayList<Books>()
try {
val document = Jsoup.connect(url).get()
val elements = document.select("li.searchResultItem")
for (i in 0 until elements.size) {
val title = elements.select("div.resultTitle")
.select("a.results")
.eq(i)
.text()
println("title = " + title.toString())
// AUTHOR:
// val author = elements.select("span.bookauthor")
// .select("a.results")
// .eq(i)
// .text()
val description = elements.select("span.bookauthor")
.select("a.results")
.eq(i)
.text()
println("description = " + description.toString())
val linkImage = "https://www.tutorialspoint.com/images/QAicon.png"
// document.baseUri() +
// elements.select("div[class=bookcover]")
// .select("img")
// .eq(i)
// .attr("src")
val additionalInfo = elements.select("span.resultPublisher")
.select("span.publishedYear")
.eq(i)
.text()
println("additionalInfo = " + additionalInfo.toString())
exampleList.add(Books(imageResource = R.drawable.ic_launcher_background, title, description, additionalInfo))
//Below 2 lines are just for another approach
val item = Books(imageResource = R.drawable.ic_launcher_background, title, description, additionalInfo)
list += item
}
GlobalScope.launch(Dispatchers.Main) {
adapter.set(exampleList)
}
} catch (e: IOException) {
Log.e("TEST EXCEPTION:::: ", e.message.toString())
}
}
}
You are loading the list into an adapter instance which is not associated with the RecyclerView, if you look closely in onActivityCreated, you will see that you are doing
adapter = ExampleAdapter() // New instance of ExampleAdapter assigned to adapter property
recycler_view.adapter = ExampleAdapter()// New instance of ExampleAdapter assigned to RV
and then you are loading the list as
adapter.set(exampleList) // This adapter is not associated with the RV
to fix this change the above lines in onActivityCreated to
adapter = ExampleAdapter()
recycler_view.adapter = adapter