0

How do I make use of application classes to store non-persistent data that can be shared among activities ? The following application has an array of type TicketClass. I would liek to be able to access and append to this array in any activities. I can't seem to find any information on this. Kindly guide me, thank you.

import android.app.Application
import java.text.SimpleDateFormat

class TicketApplication: Application()     {


    var moviesArray:ArrayList<TicketClass>? = null

    var sdf:SimpleDateFormat? = null



    init {

    }

    fun getDateFormat():SimpleDateFormat?{
        return sdf
    }

    fun addTicket(ticket:TicketClass){
        ticketArray?.add(ticket)
    }

    fun getArray():ArrayList<TicketClass>?{
        return ticketArray
    }




}
nirilo
  • 41
  • 1
  • 6
  • Never store such data in application class. as it will remain in memory even you don't require it anymore. so try to pass data between activities using **Parceable** and perform all operation over there. – Wasim K. Memon Dec 05 '18 at 12:26
  • @WasimK.Memon Thanks! However for this assignment I'm to use this only.. – nirilo Dec 05 '18 at 12:31
  • Please consider the fact that this approach you are trying to do here is considered to be bad practice, so if this is an assignment, the limitations should be specified clearly, and the task that you intend to achieve (not just what code you've written). – EpicPandaForce Dec 05 '18 at 12:53

1 Answers1

0

You can use companion object, it is like static in java. You can do something like this inside TicketApplication:

companion object {
    @JvmStatic fun addTicket(ticket:TicketClass){
        ticketArray?.add(ticket)
    }

    @JvmStatic fun getArray():ArrayList<TicketClass>?{
        return ticketArray
    }

    var ticketArray:ArrayList<TicketClass>? = null
}

init {
     ticketArray = ArrayList<TicketClass>()
}

And access it something like this:

TicketApplication.getArray()
Alex
  • 9,102
  • 3
  • 31
  • 35