I Want to get Data from https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328
But I have error
java.lang.IllegalArgumentException: Parameter specified as non-null is
null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull,
parameter data at
com.yutra.jadwalbola.last_match.LastMatchFragment.showTeamList(Unknown
Source:21) at
com.yutra.jadwalbola.last_match.LastMatchPresenter$getTeamList$1$1.invoke(LastMatchPresenter.kt:21)
at
com.yutra.jadwalbola.last_match.LastMatchPresenter$getTeamList$1$1.invoke(LastMatchPresenter.kt:8)
this is my LastMatchDBApi
object LastMatchDBApi {
fun getMatch(): String {
return Uri.parse(BuildConfig.BASE_URL).buildUpon()
.appendPath("api")
.appendPath("v1")
.appendPath("json")
.appendPath(BuildConfig.TSDB_API_KEY)
.appendPath("eventspastleague.php")
.appendQueryParameter("id", "4328")
.build()
.toString()
}
}
this is my serialized
data class LastMatch(
#SerializedName("strEvent")
var eventName: String? = null
)
this is my presenter
class LastMatchPresenter(private val view: MainView,
private val apiRepository: ApiRepository,
private val gson: Gson) {
fun getTeamList() {
view.showLoading()
doAsync {
val data = gson.fromJson(apiRepository
.doRequest(LastMatchDBApi.getMatch()),
LastMatchResponse::class.java
)
uiThread {
view.hideLoading()
view.showTeamList(data.lastMatch)
}
}
}
}
this is my response
data class LastMatchResponse(
val lastMatch: List<LastMatch>
)
this is my fragment activity
class LastMatchFragment : Fragment(), MainView {
private lateinit var progressBar: ProgressBar
private lateinit var swipeRefresh: SwipeRefreshLayout
private var lastMatch: MutableList<LastMatch> = mutableListOf()
private lateinit var adapter: MainAdapter
private lateinit var listTeam: RecyclerView
private var key : String = "4328"
companion object {
fun newInstance(): LastMatchFragment {
return LastMatchFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = UI {
linearLayout {
lparams (width = matchParent, height = wrapContent)
orientation = LinearLayout.VERTICAL
topPadding = dip(16)
leftPadding = dip(16)
rightPadding = dip(16)
// textView {
// text = "test image"
// }
relativeLayout{
lparams (width = matchParent, height = wrapContent)
listTeam = recyclerView {
lparams (width = matchParent, height = wrapContent)
layoutManager = LinearLayoutManager(ctx)
}
progressBar = progressBar {
}.lparams{
centerHorizontally()
}
}
}
}.view
adapter = MainAdapter(lastMatch)
listTeam.adapter = adapter
val request = ApiRepository()
val gson = Gson()
var presenter = LastMatchPresenter(this, request, gson)
presenter.getTeamList()
return view
}
override fun showLoading() {
progressBar.visible()
}
override fun hideLoading() {
progressBar.invisible()
}
override fun showTeamList(data: List<LastMatch>) {
lastMatch.clear()
lastMatch.addAll(data)
adapter.notifyDataSetChanged()
}
}
IF anyone have sourcode to get this data please help me
In below code you are passing list as null from LastMatchPresenter class
view.showTeamList(data.lastMatch)
By default all variables and parameters in Kotlin are non-null. If you want to pass null parameter to the method you should add ? to it's type, for example:
override fun showTeamList(data: List<LastMatch>?) {
lastMatch.clear()
lastMatch.addAll(data)
adapter.notifyDataSetChanged()
}
Related
I'm trying to show images from my Firebase Realtime Database storage. I've done this before with a previous version of my app, but the difference is how I implemented it. My adapter and arraylist class are exactly the same, but instead of using an activity I switched to using fragments.
What I essentially did was copy my old work and make the appropriate changes so I wouldn't run into errors, but unfortunately I ran into some. My images from Firebase are not showing up at all and I'm not sure what is the problem.
Adapter Class
class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>) : RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Glide.with(mContext)
.load(abstractList[position].abstract)
.into(holder.imageView)
}
override fun getItemCount(): Int {
return abstractList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imageView: ImageView = itemView.findViewById(R.id.abstractImageView)
}
companion object {
private const val Tag = "RecyclerView"
}
}
Data class
class Abstract {
var abstract: String? = null
constructor() {}
constructor(abstract: String?) {
this.abstract = abstract
}
}
Fragment in which images will be shown
class AbstractWallpapers: Fragment(), PurchasesUpdatedListener {
private lateinit var subscribeAbstract: Button
private var billingClient: BillingClient? = null
lateinit var recyclerView: RecyclerView
lateinit var abstractlist: ArrayList<Abstract>
private var recyclerAdapterAbstract: AbstractAdapter? = null
private var myRef3: DatabaseReference? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_abstract_wallpaper, container, false)
recyclerView = requireView().findViewById(R.id.abstract_recyclerView)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.abstract_recyclerView)
val layoutManager = LinearLayoutManager(requireActivity())
recyclerView.layoutManager = layoutManager
recyclerView.setHasFixedSize(true)
myRef3 = FirebaseDatabase.getInstance().reference
abstractlist = ArrayList()
ClearAll()
GetDataFromFirebase()
subscribeAbstract = view.findViewById(R.id.abstract_subscribe_btn)
subscribeAbstract.setOnClickListener {
subscribeAbstract()
}
// Establish connection to billing client
//check subscription status from google play store cache
//to check if item is already Subscribed or subscription is not renewed and cancelled
billingClient = BillingClient.newBuilder(requireActivity()).enablePendingPurchases().setListener(this).build()
billingClient!!.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
val queryPurchase = billingClient!!.queryPurchases(BillingClient.SkuType.SUBS)
val queryPurchases = queryPurchase.purchasesList
if (queryPurchases != null && queryPurchases.size > 0) {
handlePurchases(queryPurchases)
} else {
saveSubscribeValueToPref(false)
}
}
}
override fun onBillingServiceDisconnected() {
Toast.makeText(requireActivity(), "Service Disconnected", Toast.LENGTH_SHORT).show()
}
})
//item subscribed
if (subscribeValueFromPref) {
subscribeAbstract.visibility = View.GONE
} else {
subscribeAbstract.visibility = View.VISIBLE
}
}
// Code related to Firebase
#SuppressLint("NotifyDataSetChanged")
private fun GetDataFromFirebase() {
val query: Query = myRef3!!.child("Abstract")
query.addListenerForSingleValueEvent(object : ValueEventListener {
#SuppressLint("NotifyDataSetChanged")
override fun onDataChange(snapshot: DataSnapshot) {
for (dataSnapshot: DataSnapshot in snapshot.children) {
val abstract = Abstract()
abstract.abstract = dataSnapshot.child("abstract").value.toString()
abstractlist.add(abstract)
}
recyclerAdapterAbstract = abstractlist.let { AbstractAdapter(requireActivity(), it) }
recyclerView.adapter = recyclerAdapterAbstract
recyclerAdapterAbstract!!.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {}
})
if (recyclerAdapterAbstract != null) recyclerAdapterAbstract!!.notifyDataSetChanged()
}
private fun ClearAll() {
abstractlist.clear()
abstractlist = ArrayList()
}
I fixed my problem. It turns out my rules in Firebase Realtime Database rules for read were set to false instead. My code works perfect. It was only a stupid error on my part.
`Hello friends, good morning. What should I do to restart the pedometer? I saw many samples, but what they all had in common was to click on the desired view to restart the pedometer. But I do not want that to happen. The number of steps should be 0 every 24 hours. My codes:
Thanks for the code to explain
class Home : Fragment(), SensorEventListener {
lateinit var binding: FragmentHomeBinding
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f
//
private lateinit var mHandler: Handler
private var calories = 0.0
val todayDate: String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date())
val dateForCalories = "$todayDate-kcal"
override fun onResume() {
super.onResume()
running = true
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//load View model
detailsViewModel.messageTodayLiveData.observe(viewLifecycleOwner) {
binding.homeLayout.messageDay.text = it.message
}
materialDrawer()
loadData()
resetSteps()
calculateCalories()
sensorManager = requireContext().getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
private fun resetSteps() {
}
private fun saveDate() {
Constant.editor(requireContext()).putFloat(STEPNUMBER, previousTotalStep).apply()
}
private fun loadData() {
previousTotalStep = Constant.getSharePref(requireContext()).getFloat(STEPNUMBER, 0f)
}
override fun onSensorChanged(event: SensorEvent?) {
if (running)
totalStep = event!!.values[0]
val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
binding.homeLayout.txtSteps.text = ("$currentSteps")
binding.homeLayout.txtKilometers.text =
String.format(getString(R.string.meters_today), stepsToMeters(currentSteps))
binding.homeLayout.progressStep.apply {
setProgressWithAnimation(currentSteps.toFloat())
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
}
Service codes
class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f
val todayDate: String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date())
private lateinit var sharedPref: SharedPreferences
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
try {
running = true
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
} catch (e: Exception) {
}
return START_STICKY
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onSensorChanged(event: SensorEvent?) {
if (running) {
totalStep = event!!.values[0]
val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
TODO("Not yet implemented")
}
override fun stopService(name: Intent?): Boolean {
return super.stopService(name)
}
override fun onDestroy() {
val intent = Intent(this, MyPhoneReceiver::class.java)
sendBroadcast(intent)
super.onDestroy()
}
}
Broadcast codes
class MyPhoneReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action?.equals(Intent.ACTION_BOOT_COMPLETED, ignoreCase = true) == true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, MyService::class.java))
} else {
context.startService(Intent(context, MyService::class.java))
}
}
}
}
When I try to view the list of data coming from realtime firebase no information is displayed
My adapter:
class MarcacaoAdapter: RecyclerView.Adapter<MarcacaViewHolder>() {
private var items = listOf<Marcacao>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MarcacaViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_lista, parent, false)
return MarcacaViewHolder(view)
}
override fun onBindViewHolder(holder: MarcacaViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int {
return items.size
}
}
My view holder:
class MarcacaViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val textviewData = itemView.findViewById<TextView>(R.id.tvDataM)
private val textviewHora = itemView.findViewById<TextView>(R.id.tvHoraM)
fun bind (item: Marcacao){
textviewData.text = item.dia
textviewHora.text = item.hora
}
}
My activity list:
class ListaActivity : AppCompatActivity() {
private val adapterMarcacao = MarcacaoAdapter()
private var tvDataM: TextView? = null
private var tvHoraM: TextView? = null
private lateinit var mDatabaseReference: DatabaseReference
private lateinit var mRecycler : RecyclerView
private lateinit var mArrayList : ArrayList<Marcacao>
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lista)
mRecycler = findViewById(R.id.recyclerView)
mArrayList = arrayListOf<Marcacao>()
mDatabaseReference = FirebaseDatabase.getInstance().getReference("data")
}
}
I would like some help to identify why my recycler view is not loading information from firebase.
I am making android application, where i am using recyclerview inside recyclerview, all working is fine but i am getting my second adapter result at one place
Out of 4 results two results should shown in above
Problem:
In my recyclerview result shoud show like: 1[1,2,3] // this is my recyclerview inside recyclerview 2[1,2,3]
but i am getting result like 1[] 2[1,2,3 1,2,3] // but i am getting result like this
history.kt
class history : Fragment(), KodeinAware {
lateinit var recyclerView : RecyclerView
lateinit var layoutManager : LinearLayoutManager
lateinit var orid_TA_Adapter : history_adapter
lateinit var orid_TA : ArrayList<orderID_Am_ST>
lateinit var db : FirebaseFirestore
val auth = FirebaseAuth.getInstance()
val Fuser = auth.currentUser
override val kodein: Kodein by kodein { activity?.applicationContext!! }
private val factory: CustomerViewModelFactory by instance()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view= inflater.inflate(R.layout.fragment_history, container, false)
recyclerView = view?.findViewById(R.id.history)!!
layoutManager = LinearLayoutManager(activity as Context)
recyclerView.layoutManager = layoutManager
recyclerView.setHasFixedSize(true)
orid_TA = arrayListOf()
orid_TA_Adapter = history_adapter(orid_TA,requireContext())
recyclerView.adapter = orid_TA_Adapter
All_orid_TA()
return view
}
private fun All_orid_TA(){
db = FirebaseFirestore.getInstance()
db.collection("Order Details1/${Fuser?.uid}/OrderID").addSnapshotListener(object :
EventListener<QuerySnapshot> {
override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
if(error != null){
Log.e("Firestore error",error.message.toString())
return
}
for(doc: DocumentChange in value?.documentChanges!!){
if(doc.type == DocumentChange.Type.ADDED){
orid_TA.add(doc.document.toObject(orderID_Am_ST::class.java))
}
}
orid_TA_Adapter.notifyDataSetChanged()
}
})
}
}
history_adapter.kt
class history_adapter(private var oidta:ArrayList<orderID_Am_ST>, val context: Context): RecyclerView.Adapter<history_adapter.ViewHolder>() {
val fireStore = FirebaseFirestore.getInstance()
// lateinit var recyclerView : RecyclerView
lateinit var layoutManager : LinearLayoutManager
lateinit var history_product_Adapter : history_product_adapter
lateinit var history_product : ArrayList<Add_to_FireStore>
lateinit var db : FirebaseFirestore
val auth = FirebaseAuth.getInstance()
val Fuser = auth.currentUser
private val viewPool = RecyclerView.RecycledViewPool()
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val slot_time_history: TextView = itemView.findViewById(R.id.slot_time_history)
val delivery_address_history: TextView = itemView.findViewById(R.id.delivery_address_history)
val totalamount_history: TextView = itemView.findViewById(R.id.totalamount_history)
val recyclerView: RecyclerView = itemView.findViewById(R.id.product_history)
val shop_name_history: TextView = itemView.findViewById(R.id.shop_name_history)
val order_ID_history: TextView = itemView.findViewById(R.id.order_ID_history)
val order_date_history: TextView = itemView.findViewById(R.id.order_date_history)
val phone_number_history: TextView = itemView.findViewById(R.id.phone_number_history)
val cancel_order: Button = itemView.findViewById(R.id.cancel_order)
val status_order: TextView = itemView.findViewById(R.id.status_order)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.history_adapter, parent, false)
return history_adapter.ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val orderId_TA : orderID_Am_ST = oidta[position]
holder.slot_time_history.text = orderId_TA.slot_time
holder.delivery_address_history.text = orderId_TA.deliver_address
holder.totalamount_history.text = orderId_TA.total_ammount
holder.order_ID_history.text = orderId_TA.order_id
holder.order_date_history.text = orderId_TA.order_date
holder.status_order.text = orderId_TA.status
layoutManager = LinearLayoutManager(context)
//layoutManager.initialPrefetchItemCount = oidta.size
//layoutManager = LinearLayoutManager(holder.recyclerView.context, RecyclerView.VERTICAL, false)
holder.recyclerView.layoutManager = layoutManager
holder.recyclerView.setHasFixedSize(true)
history_product = arrayListOf()
history_product_Adapter = history_product_adapter(history_product, context)
holder.recyclerView.adapter = history_product_Adapter
holder.recyclerView.setRecycledViewPool(viewPool)
//All_product_List(orderId_TA.order_id)
db = FirebaseFirestore.getInstance()
db.collection("customer/user/profile").document("${Fuser?.uid}").get().addOnCompleteListener {
if(it.isSuccessful){
val shop_name = it.result["shopname"]
holder.shop_name_history.text = shop_name.toString()
holder.phone_number_history.text = Fuser?.phoneNumber.toString()
}
}
//oidta[holder.adapterPosition].order_id OID0a7bedfd469649bd9a
//db.collection("Order Details1/${Fuser?.uid}/OrderID/${orderId_TA.order_id.toString()}
db.collection("Order Details1/${Fuser?.uid}/OrderID/OID1945395f651948f186/order").addSnapshotListener(object :
EventListener<QuerySnapshot> {
override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
if(error != null){
Log.e("Firestore error",error.message.toString())
return
}
for(doc: DocumentChange in value?.documentChanges!!){
if(doc.type == DocumentChange.Type.ADDED){
//history_product.add(doc.document.toObject(Add_to_FireStore::class.java))
history_product.add(doc.document.toObject(Add_to_FireStore::class.java))
}
}
//history_product
history_product_Adapter.notifyDataSetChanged()
}
})
val order_time:String = orderId_TA.order_date.toString()
val sdf1 = SimpleDateFormat("dd/M/yyyy H:mm:ss")
val currentDate_Time = sdf1.format(Date())
val format = SimpleDateFormat("dd/M/yyyy H:mm:ss")
val diff = format.parse(currentDate_Time).time - format.parse(order_time).time
val hours:Int = (diff/3600000).toInt()
if(hours <= 5000){
if(holder.status_order.text == "cancelled"){
holder.cancel_order.isClickable = false
holder.cancel_order.setBackgroundColor(Color.GRAY)
}else{
holder.cancel_order.setOnClickListener {
val alertDialogBuilder = AlertDialog.Builder(context)
alertDialogBuilder.setTitle(Html.fromHtml("<font color='#00BFFF'>Cancel Order</font>"))
// alertDialogBuilder.setIcon(R.drawable.exit)
alertDialogBuilder.setMessage("Are you sure sure want to Cancel Order?")
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton(
Html.fromHtml("<font color='#00BFFF'>Yes</font>"),
DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(context, "Cancelling Order", Toast.LENGTH_SHORT).show()
FirebaseFirestore.getInstance().collection("Order Details1/${Fuser?.uid}/OrderID").document("${orderId_TA.order_id}").update("status","cancelled")
holder.status_order.text = orderId_TA.status
})
alertDialogBuilder.setNegativeButton(
Html.fromHtml("<font color='#00BFFF'>No</font>"),
DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(
context,
"You clicked cancel",
Toast.LENGTH_LONG
).show()
})
val alertDialog: AlertDialog = alertDialogBuilder.create()
alertDialog.show()
}
}
}else{
holder.cancel_order.setBackgroundColor(Color.GRAY)
holder.cancel_order.setOnClickListener {
Toast.makeText(context, "Can not cancel order after 5 hours", Toast.LENGTH_SHORT).show()
}
}
}
override fun getItemCount(): Int {
return oidta.size
}
}
history_product_adapter.kt
class history_product_adapter(private var prod_det1:ArrayList<Add_to_FireStore>, val context: Context): RecyclerView.Adapter<history_product_adapter.ViewHolder>() {
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val product__name: TextView = itemView.findViewById(R.id.product__name)
val product__kgsize: TextView = itemView.findViewById(R.id.product__kgsize)
val product__varientsize: TextView = itemView.findViewById(R.id.product__varientsize)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.history_product_adapter, parent, false)
return history_product_adapter.ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val orderId_TA : Add_to_FireStore = prod_det1[position]
holder.product__name.text = orderId_TA.productName
holder.product__kgsize.text = orderId_TA.kgsize
holder.product__varientsize.text = orderId_TA.varientsize
}
override fun getItemCount(): Int {
return prod_det1.size
}
}
I have a class called medicine, I got an error when writing adapter = MedicineAdapter(this, this.medicineList!!) in main activity I saw the error in run window.
My app is crashing when I want to run and I saw one error which is about adapter's line
Also, I have medicine_items it is my custom design I assigned it to the adapter in my adapter also I checked my ids but ı don t know why am I got an error
MainActivity
class MainActivity : AppCompatActivity() {
private var adapter: MedicineAdapter? = null
private var medicineList : ArrayList<Medicine>? = null
private var recyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView =
findViewById<View>(R.id.recycler) as RecyclerView
adapter = MedicineAdapter(this, this.medicineList!!)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
// Add a neat dividing line between items in the list
recyclerView!!.addItemDecoration(
DividerItemDecoration(this,
LinearLayoutManager.VERTICAL))
// set the adapter
recyclerView!!.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.addBtn -> {
val intent = Intent(this,AddNewMedicine::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
fun addMedicine(m: Medicine){
medicineList!!.add(m)
adapter!!.notifyDataSetChanged()
}
}
MyAdapter
class MedicineAdapter(
private val mainActivity: MainActivity,
private val medicineList: ArrayList<Medicine>)
: RecyclerView.Adapter<MedicineAdapter.ListItemHolder>(){
override fun onCreateViewHolder(
parent: ViewGroup, viewType: Int): ListItemHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.medicine_items, parent, false)
return ListItemHolder(itemView)
}
inner class ListItemHolder(view: View) :
RecyclerView.ViewHolder(view),
View.OnClickListener {
internal var name = view.findViewById<TextView>(R.id.name)
internal var amount = view.findViewById<TextView>(R.id.amount)
internal var description = view.findViewById<TextView>(R.id.description)
init {
view.isClickable = true
view.setOnClickListener(this)
}
override fun onClick(view: View) {
//val intentToCarPager = Intent(view!!.context, CarPagerActivity::class.java)
//view.context.startActivity(intentToCarPager)
}
}
override fun onBindViewHolder(holder: ListItemHolder, position: Int) {
val medicine = medicineList!![position]
holder.name.text = medicine.name.toString()
holder.amount.text = medicine.amount.toString()
holder.description.text = medicine.desription.toString()
}
override fun getItemCount(): Int {
if (medicineList != null) {
return medicineList.size
}
return -1
}
}
my run window
It's because here:
private var medicineList : ArrayList<Medicine>? = null
you have initialized medicineList as null and you haven't given it a proper value along the way and here:
adapter = MedicineAdapter(this, this.medicineList!!)
you have asserted that it is not null and tried to assign it to the adapter.
If you have no elements to add to your array at first, initialize it this way:
private var medicineList : ArrayList<Medicine> = arrayListOf()
and then you can add elements to it:
medicineList.add(myMedicine)