Kotlin SharedPreferences - Save ListView items and load them - android

I have a ListView with items created by
val values = ArrayList<String>().toMutableList()
val adapter = ArrayAdapter(this, R.layout.listview_text_color, values)
adapter.add(title_editText.text!!.toString() + " - " + content_editText.text!!.toString())
I need to save those ListView items and reload them again when reopen the app using SharedPreferences (not DB)
This is my actual code about SP:
fun saveData(values: Set<String>) {
val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return
with(sharedPref.edit()) {
putStringSet("test", values)
putString("title", title_editText.text!!.toString())
putString("content", content_editText.text!!.toString())
apply()
}
}
fun getData() {
val sharedPref = this.getPreferences(Context.MODE_PRIVATE) ?: return
val titleData = sharedPref.getString("title", "")
val contentData = sharedPref.getString("content", "")
Toast.makeText(this, "$titleData $contentData", Toast.LENGTH_LONG).show()
}
EDIT FOR SOLUTION
After full days of research, I went to solution:
In MainActivity.kt create you ArrayList variable as global:
class MainActivity : AppCompatActivity() {
private var values = ArrayList<String>()
... //the rest of your code
}
Then add those 2 functions:
private fun saveData() {
val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val editor = sharedPreferences.edit()
val gson = Gson()
val json = gson.toJson(values)
editor.putString("task list", json)
editor.apply()
}
private fun loadData() {
val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val gson = Gson()
val json = sharedPreferences.getString("task list", "")
val type = object: TypeToken<ArrayList<String>>() {
}.type
if(json == null)
values = ArrayList()
else
values = gson.fromJson(json, type)
}
where values is your ArrayList
To save data:
done_fab.setOnClickListener {
values.add("put your string here")
adapter.notifyDataSetChanged() //your array adapter
saveData()
}
And to load data, simply call the function in your MainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadData()
val adapter = ArrayAdapter(this, R.layout.listview_text_color, values) //your custom arrayAdapter for the listView
... //the rest of your code
}

Thank you Arfrmann for posting a working resolution that I could use. I had to modify the code to fit inside a Fragment as well as my values being a MutableList of integers. So, I thought I'd share my scenario so that others could benefit.
class NeedsmetFragment : Fragment() {
private var incorrectList = mutableListOf<Int>()
val PREFS_FILENAME = "com.app.app.prefs"
private fun saveData() {
val sharedPreferences = context!!.getSharedPreferences(PREFS_FILENAME, 0)
val editor = sharedPreferences.edit()
val gson = Gson()
val json = gson.toJson(incorrectList)
editor.putString("incorrectList", json)
editor.apply()
}
private fun loadData() {
val sharedPreferences = context!!.getSharedPreferences(PREFS_FILENAME, 0)
val gson = Gson()
val json = sharedPreferences.getString("incorrectList", "")
val type = object: TypeToken<MutableList<Int>>() {}.type
if(json == null || json == "")
incorrectList = mutableListOf<Int>()
else
incorrectList = gson.fromJson(json, type)
}
//...
x++
incorrestList.add(x)
saveData()
loadData()
thisval = incorrectList[x]
}

The proper way to save ArrayList of String to preferences is:
.putStringArrayList("test", values)
and get it
.getStringArrayList("test")

SOLUTION
After full days of research, I went to solution:
In MainActivity.kt create you ArrayList variable as global:
class MainActivity : AppCompatActivity() {
private var values = ArrayList<String>()
... //the rest of your code
}
Then add those 2 functions:
private fun saveData() {
val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val editor = sharedPreferences.edit()
val gson = Gson()
val json = gson.toJson(values)
editor.putString("task list", json)
editor.apply()
}
private fun loadData() {
val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val gson = Gson()
val json = sharedPreferences.getString("task list", "")
val type = object: TypeToken<ArrayList<String>>() {
}.type
if(json == null)
values = ArrayList()
else
values = gson.fromJson(json, type)
}
where values is your ArrayList
To save data:
done_fab.setOnClickListener {
values.add("put your string here")
adapter.notifyDataSetChanged() //your array adapter
saveData()
}
And to load data, simply call the function in your MainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadData()
val adapter = ArrayAdapter(this, R.layout.listview_text_color, values) //your custom arrayAdapter for the listView
... //the rest of your code
}
All this because SharedPreferences doesn't supports ArrayList<String> storing, so passing them with a JSON is the best option

Related

Why is the .update("field","value") not working?

If you see the read messages function in my activity class below, i wanted to update the isSeen field in firestore, but for some reason it does not work at all. My guess it requires a specific document value but that would not be possible as this a messaging app so there will be a lot of documents created.
Activity Class
class MessageActivity : AppCompatActivity() {
private lateinit var binding: ActivityMessageBinding
private lateinit var chat: ArrayList<Message>
private lateinit var messageAdapter: MessageAdapter
private lateinit var roomID: String
private lateinit var userID: String
private lateinit var recID: String
private var c: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMessageBinding.inflate(layoutInflater)
setContentView(binding.root)
userID = FirebaseAuth.getInstance().uid.toString()
recID = intent.getStringExtra("userID").toString()
val recName:String = intent.getStringExtra("userName").toString()
binding.userName.text = recName
chat = arrayListOf()
messageAdapter = MessageAdapter(chat)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
when {
userID < recID ->
{
roomID = userID + recID
}
userID.compareTo(recID) == 0 ->
{
Toast.makeText(this, "Error you are chatting with yourself!!!", Toast.LENGTH_SHORT).show()
}
else -> {
roomID = recID + userID
}
}
readMessages(userID,recID)
binding.btnSend.setOnClickListener {
val message: String = binding.textSend.text.toString()
if(message.isNotEmpty()){
sendMessage(userID,recID,message)
binding.textSend.text.clear()
}
else{
Toast.makeText(this,"You can't send empty message", Toast.LENGTH_SHORT).show()
}
}
binding.gps.setOnClickListener {
val uri = "http://maps.google.com/maps?daddr="
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
intent.setPackage("com.google.android.apps.maps")
startActivity(intent)
}
}
private fun sendMessage(sender: String, rec: String, message: String){
val db = Firebase.firestore
val time: FieldValue = FieldValue.serverTimestamp()
val msg = hashMapOf(
"userID" to sender,
"recID" to rec,
"message" to message,
"time" to time,
"roomID" to roomID,
"isSeen" to false
)
db.collection("chats").document(roomID).collection("messages").document().set(msg,SetOptions.merge())
}
private fun readMessages(userId: String, recId: String){
val rootRef = Firebase.firestore
rootRef.collection("chats").document(roomID).collection("messages").orderBy("time", Query.Direction.ASCENDING).addSnapshotListener(object : EventListener<QuerySnapshot?>
{
override fun onEvent(#Nullable documentSnapshots: QuerySnapshot?, #Nullable e: FirebaseFirestoreException?)
{
if (e != null)
{
Log.e(TAG, "onEvent: Listen failed.", e)
return
}
chat.clear()
if (documentSnapshots != null)
{
for (queryDocumentSnapshots in documentSnapshots)
{
val msg = queryDocumentSnapshots.toObject(Message::class.java)
if (msg.recID == recId && msg.userID == userId || msg.recID == userId && msg.userID == recId)
{
chat.add(msg)
}
if(msg.recID.equals(userID).and(msg.userID.equals(recID))){
rootRef.collection("chats").document(roomID).collection("messages").document().update("isSeen",true)
}
messageAdapter = MessageAdapter(chat)
binding.recyclerView.adapter = messageAdapter
}
}
}
})
}
}
Adapter Class
class MessageAdapter(private val MessageList:ArrayList<Message>):RecyclerView.Adapter<MessageAdapter.MessageViewHolder>() {
private val left = 0
private val right = 1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
return if(viewType==right){
val view1 = LayoutInflater.from(parent.context).inflate(R.layout.chat_sender_item,parent,false)
MessageViewHolder(view1)
}else{
val view2 = LayoutInflater.from(parent.context).inflate(R.layout.chat_receiver_item,parent,false)
MessageViewHolder(view2)
}
}
override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
val message:Message = MessageList[position]
holder.showMessage.text = message.message
if(position==MessageList.size-1){
if(message.isSeen)
{
holder.textSeen.text = "Seen"
}else{
holder.textSeen.text = "Delivered"
}
}else{
holder.textSeen.visibility = View.GONE
}
}
override fun getItemCount(): Int {
return MessageList.size
}
class MessageViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){
val showMessage: TextView = itemView.findViewById(R.id.showMessage)
val textSeen: TextView = itemView.findViewById(R.id.textSeen)
}
override fun getItemViewType(position: Int): Int {
val userID = FirebaseAuth.getInstance().currentUser!!.uid
return if(MessageList[position].userID==userID)
{
right
}else
{
left
}
}
}
Model Class
package com.aarondcosta99.foodreuseapp.model
data class Message(var userID:String? = "",var message:String? = "",var recID:String? = "",var isSeen:Boolean=false)
Firestore
This won't work:
rootRef.collection("chats").document(roomID).collection("messages").document().update("isSeen",true)
The document() call without any arguments creates a reference to a new non-existing document, which you then try to update. But update() only works when a document already exists, you can't use update() to create a document, so this code ends up doing nothing.
To update a document, you need to specify the complete path to that document. The fact that you need to update a lot of documents makes no difference to that fact, it just means you'll need to paths to a lot of documents.
As far as I can tell, you are trying to update the document that you read in documentSnapshots, which means you already have the DocumentReference handy and can update it with:
queryDocumentSnapshots.reference.update("isSeen",true)

Recycler View not showing JSON data in kotlin

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.

Any alternative to showing chat messages on android app

this is the chat functionality on my app but the messages aren't appearing on my app although it is getting updated in the firebase. when I hardcoded the values it is working. this is the conversation activity. I've used a chat fragment and adapter as well. But the messages are just not getting posted on the app. any alternative solutions or a solution for this would be nice.
private val firebaseDB = FirebaseFirestore.getInstance()
private val userId = FirebaseAuth.getInstance().currentUser?.uid
private val conversationAdapter = ConversationAdapter(arrayListOf(), userId)
private var chatId: String? = null
private var imageUrl: String? = null
private var otherUserId: String? = null
private var chatName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_conversation)
chatId = intent.extras.getString(PARAM_CHAT_ID)
imageUrl = intent.extras.getString(PARAM_IMAGE_URL)
chatName = intent.extras.getString(chatName)
otherUserId = intent.extras.getString(PARAM_OTHER_USER_ID)
if (chatId.isNullOrEmpty() || userId.isNullOrEmpty()) {
Toast.makeText(this, "chat room error", Toast.LENGTH_LONG).show()
finish()
}
topNameTV.text = chatName
populateImage(this, imageUrl, topPhotoIV, R.drawable.default_user)
messagesRV.apply {
setHasFixedSize(false)
layoutManager = LinearLayoutManager(context)
adapter = conversationAdapter
}
firebaseDB.collection(DATA_CHATS)
.document(chatId!!)
.collection(DATA_CHAT_MESSAGES)
.orderBy(DATA_CHAT_MESSAGE_TIME)
.addSnapshotListener{ querySnapshot, firebaseFirestoreException ->
if(firebaseFirestoreException != null){
firebaseFirestoreException.printStackTrace()
return#addSnapshotListener
}else{
if (querySnapshot != null){
for(change in querySnapshot.documentChanges){
when(change.type){
DocumentChange.Type.ADDED -> {
val message = change.document.toObject(Convo::class.java)
if(message != null){
conversationAdapter.addMessage(message)
messagesRV.post {
messagesRV.smoothScrollToPosition(conversationAdapter.itemCount -1)
}
}
}
}
}
}
}
}
}
fun onSend(v: View) {
if (!messageET.text.isNullOrEmpty()){
val message = Convo(userId, messageET.text.toString(), System.currentTimeMillis())
firebaseDB.collection(DATA_CHATS).document(chatId!!)
.collection(DATA_CHAT_MESSAGES)
.document()
.set(message)
messageET.setText("",TextView.BufferType.EDITABLE)
}
}
companion object {
private val PARAM_CHAT_ID = "Chat id"
private val PARAM_IMAGE_URL = "Image url"
private val PARAM_OTHER_USER_ID = "Other user id"
private val PARAM_CHAT_NAME = "Chat name"
fun newIntent(context: Context?, chatId: String?, imageUrl: String?, otherUserId: String?
chatName: String?): Intent{
val intent = Intent(context,ConversationActivity::class.java)
intent.putExtra(PARAM_CHAT_ID,chatId)
intent.putExtra(PARAM_IMAGE_URL, imageUrl)
intent.putExtra(PARAM_OTHER_USER_ID, otherUserId)
intent.putExtra(PARAM_CHAT_NAME, chatName)
return intent
}
}
}

how to filter list data in descending order in kotlin?

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

How to display content of listitem on other activity on onItemClickListener, when we have already loaded listview?

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

Categories

Resources