Why is my RecycleView not working as expected - android

I am having an exam and this code won't work for me.
My RecycleView won't work and I don't know how to save the deposit amount and minus the withdrow from the amount that already giving. This is the mainAcitvity file and RvAdapter file:
MainActivity.kt
package com.example.anhar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var clRoot: ConstraintLayout
private lateinit var bignum: TextView
private lateinit var cash: ArrayList<String>
private lateinit var rvMoney: RecyclerView
private lateinit var diposte: EditText
private lateinit var dipbtn: Button
private lateinit var withdrow: EditText
private lateinit var withbtn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
clRoot = findViewById(R.id.clRoot)
cash = ArrayList()
rvMoney = findViewById<RecyclerView>(R.id.rvMoney)
bignum = findViewById(R.id.amount)
rvMoney.adapter = RvAdapter(this)
rvMoney.layoutManager = LinearLayoutManager(this)
diposte = findViewById(R.id.dip)
dipbtn = findViewById(R.id.dipbtn)
withdrow = findViewById(R.id.with)
withbtn = findViewById(R.id.withbtn)
diposte.setOnClickListener { adddipMessage() }
withdrow.setOnClickListener { addwidMessage() }
private fun addwidMessage() {
val w = withdrow.text
if (w.isNotEmpty())
bignum.text = " - ${withdrow.text}"
withdrow.text.clear()
withdrow.clearFocus()
}
private fun adddipMessage() {
val d = diposte.text
if (d.isNotEmpty())
bignum.text = " + ${diposte.text}"
diposte.text.clear()
diposte.clearFocus()
}
}
This is for the RecycleView and I don't know why it is not working.
RvAdapter.kt
package com.example.anhar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.rvmain.view.*
class RvAdapter(private val money: ArrayList<String>): RecyclerView.Adapter<RvAdapter.ItemViewHolder>() {
class ItemViewHolder(itemView: View): RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
return ItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.rvmain,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val moneys = money[position]
holder.itemView.apply {
rvMoney.text = moneys
}
}
override fun getItemCount() = money.size
}

rvMoney.adapter = RvAdapter(this) // wrong way to pass list
You must pass your list here.
Change constructor invocation like that
rvMoney.adapter = RvAdapter(listOf("Money1", "Money2"))

Related

listOf() unresolved reference

I am creating a memory game application. This is my code. This first code is MemoryBoardAdapter.
```package com.example.memory
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import androidx.recyclerview.widget.RecyclerView
import androidx.cardview.widget.CardView
import com.example.memory.models.BoardSize
import java.lang.Math.min
class MemoryBoardAdapter(private val Context: Context, private val boardSize: BoardSize, private val cardImages: List<Int>) :
RecyclerView.Adapter<MemoryBoardAdapter.ViewHolder>() {
companion object {
private const val MARGIN_SIZE = 10
private const val TAG = "MemoryBoardAdapter"
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val cardWidth = parent.width/boardSize.getWidth() - (2 * MARGIN_SIZE)
val cardHeight = parent.height/boardSize.getHeight() - (2 * MARGIN_SIZE)
val cardSideLength = min(cardWidth, cardHeight)
val view = LayoutInflater.from(Context).inflate(R.layout.memory_card, parent, false)
val layoutParams = view.findViewById<CardView>(R.id.cardView).layoutParams as ViewGroup.MarginLayoutParams
layoutParams.width = cardSideLength
layoutParams.height = cardSideLength
layoutParams.setMargins(MARGIN_SIZE, MARGIN_SIZE, MARGIN_SIZE, MARGIN_SIZE)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount() = boardSize.numCards
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val imageButton = itemView.findViewById<ImageButton>(R.id.imageButton)
fun bind(position: Int) {
imageButton.setImageResource(cardImages[position])
imageButton.setOnClickListener{
Log.i(TAG,"Clisked on position $position")
}
}
}
}```
This is the main activity.
```package com.example.memory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.memory.models.BoardSize
import com.example.memory.utils.DEFAULT_ICONS
class MainActivity : AppCompatActivity() {
private lateinit var rvBoard: RecyclerView
private lateinit var tvNumMoves: TextView
private lateinit var tvNumPairs: TextView
private var boardSize: BoardSize = BoardSize.MEDIUM
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvBoard = findViewById(R.id.rvBoard)
tvNumMoves = findViewById(R.id.tvNumMoves)
tvNumPairs = findViewById(R.id.tvNumPairs)
val chosenImages = DEFAULT_ICONS.shuffled().take(boardSize.getNumPairs())
val randomizedImages = (chosenImages + chosenImages).shuffled()
rvBoard.adapter = MemoryBoardAdapter(this,boardSize,randomizedImages)
rvBoard.setHasFixedSize(true)
rvBoard.layoutManager = GridLayoutManager(this,boardSize.getWidth())
}
}```
My error occurred in this Constants.kt file. Here the method listOf() is not been implemented and showing error. It is asking to rename the reference or to create a function. If I create a function it is showing error in main activity.
```package com.example.memory.utils
import com.example.memory.R
val DEFAULT_ICONS = listOf(
R.drawable.cloud,
R.drawable.dining,
R.drawable.eye,
R.drawable.face,
R.drawable.flight,
R.drawable.friends,
R.drawable.heart,
R.drawable.key,
R.drawable.phone,
R.drawable.rewind,
R.drawable.star,
R.drawable.volume
)```
How to resolve this error??

RecyclerView: No adapter attached; skipping layout - kotlin

I know this problem has been posted but all seemed to be posted in java code. I'm just trying to implement a small example recyclerView. Not sure what I'm doing incorrect, any insight would be great, TIA.
MainActivity.kt
package com.wildcardev.androidtest1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.wildcardev.androidtest1.adapters.RecyclerAdapter
import com.wildcardev.androidtest1.databinding.ActivityMainBinding
import com.wildcardev.androidtest1.models.TestDataObj
fun addDataToList(arrayList:ArrayList<TestDataObj>): ArrayList<TestDataObj>{
arrayList.add(TestDataObj("tes1", "test2", "test3"))
arrayList.add(TestDataObj("test2", "testt2", "testt2"))
arrayList.add(TestDataObj("tes12", "test22", "test32"))
arrayList.add(TestDataObj("tes13", "test23", "test33"))
arrayList.add(TestDataObj("tes14", "test24", "test34"))
arrayList.add(TestDataObj("tes15", "test25", "test35"))
return arrayList
}
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
val testList: ArrayList<TestDataObj> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
val list = addDataToList(testList)
Log.d("TEST1","$list")
Log.d("TEST1","${binding.recyclerView}")
binding.recyclerView.layoutManager = LinearLayoutManager(this#MainActivity)
val adapter = RecyclerAdapter(list)
binding.recyclerView.adapter = adapter
}
}
TestDataObj.kt
package com.wildcardev.androidtest1.models
data class TestDataObj(
val title: String,
val description: String,
val date: String
)
RecyclerAdapter.kt
package com.wildcardev.androidtest1.adapters
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.wildcardev.androidtest1.R
import com.wildcardev.androidtest1.models.TestDataObj
class RecyclerViewHolder(view: View): RecyclerView.ViewHolder(view){
var title: TextView = view.findViewById(R.id.title)
var description: TextView = view.findViewById(R.id.description)
var date: TextView = view.findViewById(R.id.date)
}
class RecyclerAdapter(private var list: ArrayList<TestDataObj>): RecyclerView.Adapter<RecyclerViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
Log.d("onCreateView", "INHOLDERcreate")
val view = LayoutInflater.from(parent.context).inflate(R.layout.activity_main, parent, false)
return RecyclerViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
Log.d("ADAPTER", "INBINDfunc")
val item = list[position]
holder.title.text = item.title
holder.description.text = item.description
holder.date.text = item.date
}
override fun getItemCount(): Int {
Log.d("COUNT",".getItemCountcalled")
return list.size
}
}
Try
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
I fixed my issue. When using viewBinding/dataBinding, you need to pass dataBinding to the viewHolder. Unfortunately I did not get this as I was just following tutorials that are using synthetic imports. So I changed my Adapter code to the following
RecyclerAdapter.kt
package com.wildcardev.androidtest1.adapters
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.wildcardev.androidtest1.models.TestDataObj
import com.wildcardev.androidtest1.databinding.ListItemBinding
class RecyclerViewHolder(viewDataBinding: ListItemBinding): RecyclerView.ViewHolder(viewDataBinding.root){
var title: TextView? = viewDataBinding.title
var description: TextView? = viewDataBinding.description
var date: TextView? = viewDataBinding.date
}
class RecyclerAdapter(private var list: ArrayList<TestDataObj>): RecyclerView.Adapter<RecyclerViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
Log.d("onCreateView", "INHOLDERcreate")
val binding = ListItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return RecyclerViewHolder(binding)
}
override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
Log.d("ADAPTER", "INBINDfunc $holder")
val item = list[position]
holder.title?.text = item.title
holder.description?.text = item.description
holder.date?.text = item.date
}
override fun getItemCount(): Int {
Log.d("COUNT",".getItemCountcalled ${list.size}")
return list.size
}
}

Recycler view data not loading on screen

I'm trying to show the recycler view's data on my app. The thing is, even though the NetworkStatus is successful (I can tell because I don't get the toast's message and the loader disappears and I can also see the data in the logcat), the info is not displayed. I am not sure if the error is in the way I'm calling the recycler view on my MainActivity or in the RecyclerAdapter but any idea as to where the problem is would be very helpful.
This is the RecyclerAdapter:
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.app.mortyapp.databinding.ItemDetailBinding
class RecyclerAdapter(private var characterList: List<Character>): RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerAdapter.ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ItemDetailBinding.inflate(
layoutInflater,
parent,
false
)
return ViewHolder(binding)
}
override fun getItemCount(): Int = characterList.size
override fun onBindViewHolder(holder: RecyclerAdapter.ViewHolder, position: Int) {
holder.bind(characterList[position])
}
fun setCharacterList(characterList: List<Character>){
this.characterList = characterList
notifyDataSetChanged()
}
inner class ViewHolder(
private val binding: ItemDetailBinding
) : RecyclerView.ViewHolder(binding.root){
fun bind(character: Character) {
with(binding){
val itemName: TextView = binding.tvName
val itemGender: TextView = binding.tvGender
itemName.text = character.name
itemGender.text = character.gender
}
}
}
}
This is the MainActivity:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.mortyapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val characters = mutableListOf<Character>()
private lateinit var progressBar: ProgressBar
private lateinit var recyclerAdapter: RecyclerAdapter
private val viewModel: MainViewModel by viewModels(
factoryProducer = {MainViewModelFactory()}
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
progressBar = binding.ProgressBar
progressBar.visibility = View.INVISIBLE
setObservers()
initRecyclerView()
}
private fun initRecyclerView() {
with(binding.rvCharacters){
layoutManager = LinearLayoutManager(context)
recyclerAdapter = RecyclerAdapter(characters).apply {
setCharacterList(characters)
}
}
}
private fun setObservers(){
viewModel.characterList.observe(this, Observer {
when(it.status){
NetworkStatus.LOADING ->{
//show loading state
progressBar.visibility = View.VISIBLE
}
NetworkStatus.SUCCESS -> {
//hide loading state
progressBar.visibility = View.INVISIBLE
//render character list
recyclerAdapter.setCharacterList(characters)
}
NetworkStatus.ERROR -> {
//show error message
Toast.makeText(this,"Error loading content", Toast.LENGTH_SHORT).show()
//hide loading state
progressBar.visibility = View.INVISIBLE
}
}
})
}
}
API response:
import com.google.gson.annotations.SerializedName
data class Character (
#SerializedName("id") val id: Int,
#SerializedName("name") val name: String,
#SerializedName("gender") val gender: String
)
data class CharacterListResponse(
#SerializedName("results") val results: List<Character>
)
Remote data source:
package com.app.mortyapp
import com.app.mortyapp.Model.CharacterService
import com.app.mortyapp.Model.RetrofitServices
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class CharacterRemoteDataSource {
fun getCharacterList(networkResponse: NetworkResponse<List<Character>>) {
val service = RetrofitServices.instance
.create(CharacterService::class.java)
.getCharacterList()
service.enqueue(object : Callback<CharacterListResponse> {
override fun onResponse(
call: Call<CharacterListResponse>,
response: Response<CharacterListResponse>
) {
val resource = response.body()?.run {
if (results.isNotEmpty())
Resource(NetworkStatus.SUCCESS, results)
else
Resource(NetworkStatus.ERROR)
} ?: run {
Resource(NetworkStatus.ERROR)
}
networkResponse.onResponse(resource)
}
override fun onFailure(call: Call<CharacterListResponse>, t: Throwable) {
networkResponse.onResponse(Resource(NetworkStatus.ERROR, message = t.message))
}
})
}
}
interface NetworkResponse<T> {
fun onResponse(value: Resource<T>)
}
Set adapter for Recyclerview in
setupRecylerview ()
adapter = recyclerAdapter
NetworkStatus.SUCCESS -> {
//hide loading state
progressBar.visibility = View.INVISIBLE
//render character list
recyclerAdapter.setCharacterList(characters)
recyclerAdapter.notifydatasetchanged()//add this line
}
I think most problems found with recyclerView isn't linked to it, but with some adjourning codes. For example, a very similar problem was solved by finding out that the adapter POJO class was retrieving 0 rather than the actual size of the array list.
See the solved problem here:
Android Recycler View not loading Data (Peculiar problem, Not a Duplicate)

intent.putExtra: None of the following functions can be called with the arguments supplied

I'm trying to pass data from one activity to another through an intent with putExtra. The thing is, I get the error that says: None of the following functions can be called with the arguments supplied.
I'm not sure why it's not working, since the variable that I'm referencing is in the viewholder. Any clue as to what's going on and how to fix it would help a lot.
This is my recycler adapter:
package com.example.newsapp
import android.content.Intent
import android.icu.text.CaseMap
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.newsapp.databinding.NewsItemBinding
import com.squareup.picasso.Picasso
class RecyclerAdapter (
private var Titles: List<String>,
private var Images: List<String>,
private var Authors: List<String>,
private var Descriptions: List<String>
) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>(){
inner class ViewHolder(
view: View
): RecyclerView.ViewHolder(view){
private val binding = NewsItemBinding.bind(view)
val itemTitle: TextView = binding.tvTitle
val itemImage: ImageView = binding.ivNewsImage
fun bind(urlToImage:String){
Picasso.get().load(urlToImage).into(binding.ivNewsImage)
}
init {
itemImage.setOnClickListener{
val intent = Intent(view.context, PostActivity::class.java)
intent.putExtra("title",itemTitle)
view.context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemTitle.text = Titles[position]
val itemImage = Images[position]
holder.bind(itemImage)
}
override fun getItemCount(): Int {
return Titles.size
}
}
The part with the issue is this one:
init {
itemImage.setOnClickListener{
val intent = Intent(view.context, PostActivity::class.java)
intent.putExtra("title",itemTitle) view.context.startActivity(intent)
}
}
This is my main activity:
package com.example.newsapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.newsapp.databinding.ActivityMainBinding
import kotlinx.coroutines.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var adapter: RecyclerAdapter
private val newsTitles = mutableListOf<String>()
private val newsImages = mutableListOf<String>()
private val newsAuthors = mutableListOf<String>()
private val newsDescriptions = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
makeAPIRequest()
}
private fun initRecyclerView() {
adapter = RecyclerAdapter( newsTitles, newsImages)
binding.rvNews.layoutManager = LinearLayoutManager(this)
binding.rvNews.adapter = adapter
}
private fun addToList(title:String, image:String, author:String, description:String){
newsTitles.add(title)
newsImages.add(image)
newsAuthors.add(author)
newsDescriptions.add(description)
}
private fun makeAPIRequest() {
val api = Retrofit.Builder()
.baseUrl("https://newsapi.org/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(APIService::class.java)
GlobalScope.launch(Dispatchers.IO){
val response = api.getNews()
val posts = response.body()
try{
if (posts != null) {
for(art in posts.Articles){
Log.i("Main Activity", "Result = $art")
addToList(art.Title,art.urlToImage, art.Author, art.Description)
}
}
withContext(Dispatchers.Main){
initRecyclerView()
}
} catch (e:Exception){
Log.e("Main Activity", e.toString())
}
}
}
}
intent.putExtra("title",itemTitle)
Here, itemTitle is a TextView. You cannot pass a TextView between activities. You could switch to:
intent.putExtra("title",itemTitle.text)
...to put the text from the TextView into the extra.
Also, you might want to consider whether these should be separate activities or just two fragments (or composables) in a single activity.

Adapter doesn't load my Room db list

I was following some guide and tweaking variable name to fit my own project. My problem was most people dont appears to load from Room db into an adapter so when trying to do upon opening the apps my view appears empty. while i checked the DB using DB browser for SQLite i can see my db contain 7 items.
Main activity
package com.example.android.budgetproject
import android.arch.persistence.room.RoomDatabase
import android.content.Context
import android.content.SharedPreferences
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.example.android.budgetproject.databinding.ActivityMainBinding
import com.example.android.budgetproject.popUp.DepenseDetails
import com.example.android.budgetproject.popUp.NewBudget
class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener, BudgetVM.NewButtonClick {
lateinit var budget : SharedPreferences
var budgetTotal: String? = null
val vm = BudgetVM()
lateinit var db: RoomDatabase
lateinit var adapter: TransactionAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
binding.vm = vm
//Get the Total Budget in the shared pref and display it
budget = getSharedPreferences("Budget", Context.MODE_PRIVATE)
budget.registerOnSharedPreferenceChangeListener(this)
budgetTotal = budget.getString("BudgetTotal", null)
adapter = TransactionAdapter()
//Open Dialog if new user.
if(budgetTotal == null) {
NewBudget.createPopUp(this)
} else {
vm.budgetTotal.set(budgetTotal)
}
vm.listener = this
//Room
db = MyDatabase.getInstance()
//Adapter
val handler = Handler()
Thread({
val transactionFromDb = MyDatabase.mInstance?.transactionDao()?.getAllTransaction()
handler.post({
if (transactionFromDb != null) adapter.addTransaction(transactionFromDb)
})
}).start()
adapter.notifyDataSetChanged()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
vm.budgetTotal.set(budgetTotal)
}
override fun newTransactionClicked(){
DepenseDetails.createTransaction(this)
}
}
The Dao:
package com.example.android.budgetproject
import android.arch.persistence.room.*
import com.example.android.budgetproject.Transaction
import android.arch.persistence.room.Delete
import android.arch.persistence.room.Dao
#Dao
interface TransactionDao {
#Query("SELECT * FROM `transaction`")
fun getAllTransaction(): List<Transaction>
#Query("SELECT * FROM `transaction` where uid IN (:transactionId)")
fun findTransactionById(transactionId: IntArray): List<Transaction>
#Insert(onConflict = 1)
fun insertTransaction(transaction: Transaction)
#Delete
fun deleteTransaction(transaction: Transaction)
}
The Adapter:
package com.example.android.budgetproject
import android.support.v7.recyclerview.extensions.ListAdapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_main.view.*
import kotlinx.android.synthetic.main.row_depense_fragment.view.*
/**
* Created by olivier on 2018-03-13.
*/
class TransactionAdapter(private val clickListener: ButtonClick? = null):
ListAdapter<Transaction, TransactionAdapter.ViewHolder>(TransactionDiffCallback()) {
interface ButtonClick{
fun clicked(id: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.row_depense_fragment, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
fun bind(transaction: Transaction){
itemView.tv_depense_description.text = transaction.description
itemView.tv_depense.text = transaction.depense
itemView.tv_depense_date.text = transaction.date
itemView.setOnClickListener{
clickListener?.clicked(adapterPosition)
}
}
}
private var transactionList = ArrayList<Transaction>()
fun addTransaction(list: List<Transaction>){
transactionList.clear()
transactionList.addAll(list)
notifyDataSetChanged()
}
}
And the util i use to create DB item.
package com.example.android.budgetproject
import android.os.AsyncTask
import android.widget.Toast
class TransactionCreation {
fun transactionCreation(depense: String, description: String, date: String){
val newTransaction = Transaction(depense, description, date)
val db = MyDatabase
object : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void?): Void? {
db.getInstance().transactionDao().insertTransaction(newTransaction)
return null
}
override fun onPostExecute(result: Void?) {
super.onPostExecute(result)
Toast.makeText(BudgetApplication.getContext(), "Transaction saved", Toast.LENGTH_SHORT)
}
}.execute()
}
}
Here's also a link to the project github should be up to date.
https://github.com/OlivierLabelle/BudgetProject
Thanks for checking.
Set notifyDataSetChanged within the thread in your MainActivity via the handler.

Categories

Resources