Main activity:
val turminha : Turma = this.abrirArquivo()
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = AlunoAdapter(this,turminha.alunos)
floatingActionButton.setOnClickListener({
val i = Intent(this, ActivityAddAluno::class.java)
i.putExtra("turma", turminha)
startActivity(i)
})
ActivityAddAluno
class ActivityAddAluno : AppCompatActivity() {
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_aluno)
mBtnSalvarAluno.setOnClickListener{
var name = mEdtNomeAluno.text.toString()
var matricula = mEdtMatriculaAluno.text.toString()
toast("Nome: $name \n," +
"Matricula: $matricula")
turma.addAluno(Aluno(name, matricula))
}
}
Class Aluno
class Aluno : Serializable {
var disciplinas: ArrayList<Disciplina>? = null
private set
var nome: String? = null
var matricula: String? = null
constructor() {
disciplinas = ArrayList()
}
constructor(nome: String, matricula: String) {
this.nome = nome
this.matricula = matricula
disciplinas = ArrayList()
}
Class Turma
class Turma() : Serializable {
val alunos: ArrayList<Aluno>
init {
alunos = ArrayList()
}
fun addAluno(aluno: Aluno) {
alunos.add(aluno)
}
When I try to access the other activity passing my Turma object in floatbutton, the app stops working. Logcat says the problem is in the code part:
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
logcat:
FATAL EXCEPTION: main
Process: com.example.thial.estudandokotlin, PID: 3428
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.thial.estudandokotlin/com.example.thial.estudandokotlin.ActivityAddAluno}:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
How can i resolve this?
Actually your problem is happening here as per your log cat messages.
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
Here the Value "i" is null and on top of it your trying to take the getSerializableExtra() String.
Where exactly your calling this lines in ActivityAddAluno class ? It must be inside the onCreate function not in the constructor. (As per Joshua stated)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//...
var i = getIntent()
if(i!=null)
{
private var turma = i.getSerializableExtra("turma") as Turma
}
}
Here is one of the example Switching between Activities along with data using Kotlin
Related
class MainActivity() : AppCompatActivity() {
lateinit var tumBurcBilgileri: ArrayList<Burc>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var myBaseAdapter = BurclarBaseAdapter(this, tumBurcBilgileri)
ListBurclar.adapter = myBaseAdapter
}
private fun veriKaynagiHazirla(){
tumBurcBilgileri=ArrayList<Burc>(12)
var burclar = resources.getStringArray(R.array.Burc)
var BurcTarihleri = resources.getStringArray(R.array.burcTarih)
var BurcResimleri = arrayOf(R.drawable.koc1, R.drawable.boga2, R.drawable.ikizler3,
R.drawable.yengec4, R.drawable.aslan5,
R.drawable.basak6, R.drawable.terazi7, R.drawable.akrep8,
R.drawable.yay9, R.drawable.oglak10, R.drawable.kova11,
R.drawable.balik12)
var BüyükBurcResim = arrayOf(R.drawable.koc_buyuk1, R.drawable.boga_buyuk2,
R.drawable.ikizler_buyuk3, R.drawable.yengec_buyuk4, R.drawable.aslan_buyuk5,
R.drawable.basak_buyuk6, R.drawable.terazi_buyuk7, R.drawable.akrep_buyuk8, R.drawable.yay_buyuk9,
R.drawable.oglak_buyuk10, R.drawable.kova_buyuk11, R.drawable.balik_buyuk12)
var burcGenelÖzellikler = resources.getStringArray(R.array.burcGenelOzellikler)
for (i in 0..11){
var arayListeAtanacakBurc=Burc(burclar[i], BurcTarihleri[i], BurcResimleri[i], BüyükBurcResim[i],
burcGenelÖzellikler[i])
tumBurcBilgileri.add(arayListeAtanacakBurc)
}
}
}
Logcat Log:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.burlar/com.example.burlar.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property tumBurcBilgileri has not been initialized
You are getting the error because you have to intitialise the tumBurcBilgileri in onCreate() method as you have used lateinit for the variable. You can put this:-
tumBurcBilgileri=ArrayList<Burc>(12)
in onCreate() method
You are trying to access a lateinit properly before initializing it. Prepare the tumBurcBilgileri ArrayList before setting the adapter.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
private fun veriKaynagiHazirla(){
tumBurcBilgileri=ArrayList<Burc>(12)
var burclar = resources.getStringArray(R.array.Burc)
var BurcTarihleri = resources.getStringArray(R.array.burcTarih)
var BurcResimleri = arrayOf(R.drawable.koc1, R.drawable.boga2, R.drawable.ikizler3,
R.drawable.yengec4, R.drawable.aslan5,
R.drawable.basak6, R.drawable.terazi7, R.drawable.akrep8,
R.drawable.yay9, R.drawable.oglak10, R.drawable.kova11,
R.drawable.balik12)
var BüyükBurcResim = arrayOf(R.drawable.koc_buyuk1, R.drawable.boga_buyuk2,
R.drawable.ikizler_buyuk3, R.drawable.yengec_buyuk4, R.drawable.aslan_buyuk5,
R.drawable.basak_buyuk6, R.drawable.terazi_buyuk7, R.drawable.akrep_buyuk8, R.drawable.yay_buyuk9,
R.drawable.oglak_buyuk10, R.drawable.kova_buyuk11, R.drawable.balik_buyuk12)
var burcGenelÖzellikler = resources.getStringArray(R.array.burcGenelOzellikler)
for (i in 0..11){
var arayListeAtanacakBurc=Burc(burclar[i], BurcTarihleri[i], BurcResimleri[i], BüyükBurcResim[i],
burcGenelÖzellikler[i])
tumBurcBilgileri.add(arayListeAtanacakBurc)
}
// set the adapter after the **tumBurcBilgileri** ArrayList is ready.
var myBaseAdapter = BurclarBaseAdapter(this, tumBurcBilgileri)
ListBurclar.adapter = myBaseAdapter
}
You are not calling the function in the onCreate where the initialization of the lateinit variable is called.
In a lateinit variable you have to assign a value to it before you use it
lateinit var tumBurcBilgileri: ArrayList<Burc>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
veriKaynagiHazirla() // call the function here
var myBaseAdapter = BurclarBaseAdapter(this, tumBurcBilgileri)
ListBurclar.adapter = myBaseAdapter
}
I've been struggling with the problem for a long time and I can't solve it.I'm in EditActivity trying to add a key to the data from the firebase that I get from it with the help of Ad and process it using the AdsManager.
The key should not be equal to zero. In this line I check if the key is zero, then the Firebase writes data to empty.db.child (ad.key?: "Empty"). SetValue (ad). When I load the data to the Firebase, it shows them empty. Without displaying the key. You know what the problem is?
Ad
data class Ad(
var user_id : String? = null ,
var name : String? = null ,
var button1 : String? = null ,
val textTex : String? = null ,
val textk : String? = null ,
val description : String? = null,
val name_ads: String?=null,
val key :String? =null
)
AdsManager
class AdsManager(val readDataColbak : ReadDataColbak?) {
private lateinit var auth: FirebaseAuth
val db =Firebase.database.getReference("main")
fun pubilshAd(ad :Ad) {
db.child(ad.key?: "empty").setValue(ad)
}
fun ReadDataDb() {
db.addListenerForSingleValueEvent(object :ValueEventListener{
override fun onDataChange(snapshot : DataSnapshot) {
val adArray =ArrayList<Ad>()
for (item in snapshot.children){
val ad =item.children.iterator().next().child("ad").getValue(Ad::class.java)
adArray.add(ad !!)
}
readDataColbak?.readData(adArray)
}
override fun onCancelled(error : DatabaseError) {
}
})
}
}
EditActivity1
class EditActivity1: AppCompatActivity(), FfragmentInterfes{
lateinit var mBinder : ActivityEdit1Binding
private var dialog=D()
private var chooseImageFrog:FragmentList? =null
val adsManager = AdsManager(null)
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
imageAdapter = ImageAdapter()
mBinder=ActivityEdit1Binding.inflate(layoutInflater)
setContentView(mBinder.root)
init()
}
fun onClickPublish(view : View) {
adsManager.pubilshAd(fillAd())
}
private fun fillAd() : Ad {
var ad : Ad
mBinder.apply {
ad= Ad(
name_ads.text.toString(),
user_id.text.toString(),
name.text.toString(),
button1.text.toString(),
description.text.toString(),
textk.text.toString(),
adsManager.db.push().key
)
}
return ad
}
The result is always return null, I don't know what mistake, I have seen other people problems I am not getting what I need exactly.
class DatabaseLists(private val context: Context?) {
private lateinit var database: SQLiteDatabase
val getPrayerContentList: ArrayList<PrayerModel>
#SuppressLint("Recycle")
get() {
database = DatabaseOpenHelper(context).readableDatabase
val cursor: Cursor = database.query(
"table_prayer",
null,
null,
null,
null,
null,
null,
null
)
val contentList = ArrayList<PrayerModel>()
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
val contents = PrayerModel(
cursor.getString(cursor.getColumnIndex("prayer_name")),
cursor.getString(cursor.getColumnIndex("ayah_name")),
cursor.getString(cursor.getColumnIndex("arabic")),
cursor.getString(cursor.getColumnIndex("latin")),
cursor.getString(cursor.getColumnIndex("translate")),
cursor.getString(cursor.getColumnIndex("description"))
)
contentList.add(contents)
cursor.moveToNext()
if (cursor.isClosed) {
cursor.close()
}
}
}
return contentList
}
class PrayerActivity : AppCompatActivity(), MainContract.MainView {
private lateinit var binding: ActivityPrayerBinding
private var database: SQLiteDatabase? = null
private lateinit var preferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
lateinit var carlist: ArrayList<PrayerModel>
private lateinit var prayerContentList: MutableList<PrayerModel>
private lateinit var prayerAdapter: PrayerAdapter
private lateinit var mainPresenterImpl: MainPresenterImpl
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_prayer)
setSupportActionBar(binding.toolbar)
preferences = PreferenceManager.getDefaultSharedPreferences(this)
editor = preferences.edit()
PreferenceManager.getDefaultSharedPreferences(this)
database = DatabaseOpenHelper(this).readableDatabase
prayerContentList = DatabaseLists(this).getPrayerContentList
mainPresenterImpl = MainPresenterImpl(this, this)
initMainContent()
}
override fun initMainContent() {
val verticalLayout = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
binding.rvMainContent.layoutManager = verticalLayout
prayerAdapter = PrayerAdapter(this, prayerContentList)
binding.rvMainContent.adapter = prayerAdapter
}
}
data class PrayerModel (
val strPrayerName: String?,
val strAyahName: String?,
val strContentArabic: String?,
val strContentLatin: String?,
val strContentTranslation: String?,
val strContentDescription: String?)
myAdapter
class PrayerAdapter(context: Context, private val prayerContentList: MutableList<PrayerModel>) :
RecyclerView.Adapter<PrayerViewHolder>() {
private val context: Context? = null
private val inflater = LayoutInflater.from(context)
private var currentIndex: Int = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PrayerViewHolder {
return PrayerViewHolder(inflater.inflate(R.layout.item_prayer_content, parent, false))
}
override fun getItemCount(): Int {
return prayerContentList.size
}
override fun onBindViewHolder(holder: PrayerViewHolder, position: Int) {
val strContentArabic = prayerContentList[position].strContentArabic
val strContentLatin = prayerContentList[position].strContentLatin
val strContentTranslation = prayerContentList[position].strContentTranslation
val strContentDescription = prayerContentList[position].strContentDescription
val strPrayerName = prayerContentList[position].strPrayerName
val strAyahName = prayerContentList[position].strAyahName
holder.tvContentPrayerName.text = strPrayerName
holder.tvContentAyahName.text = strAyahName
holder.itemView.setOnClickListener { v ->
val context: Context = v.context
val intent = Intent(context, PrayerReadActivity::class.java)
intent.putExtra("ARABIC_TEXT", strContentArabic?.get(position))
intent.putExtra("LATIN_TEXT", strContentLatin!![position])
intent.putExtra("TRANSLATION_TEXT", strContentTranslation!![position])
intent.putExtra("DESCRIPTION_TEXT", strContentDescription!![position])
context.startActivity(intent)
Log.d(TAG, "-->name = $strContentArabic")
}
}
}
my 2Activity can have code like this, and trying to get that string extra in another activity but is returning null?
class PrayerReadActivity() : AppCompatActivity() {
private var database: SQLiteDatabase? = null
private lateinit var prayerContentList: MutableList<PrayerModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_prayer_read)
LockOrientation(this).lock()
PreferenceManager.getDefaultSharedPreferences(this)
database = DatabaseOpenHelper(this).readableDatabase
prayerContentList = DatabaseLists(this).getPrayerContentList
val extras = intent.extras
if (null != extras) {
val arabic = extras.getString("ARABIC_TEXT").toString()
val latin = extras.getString("LATIN_TEXT").toString()
val translation = extras.getString("TRANSLATION_TEXT").toString()
val description = extras.getString("DESCRIPTION_TEXT").toString()
Log.d(ContentValues.TAG, "-->arabic = $arabic")
tvContentArabic2.text = arabic
tvContentLatin2.text = latin
tvContentTranslation2.text = translation
tvContentDescription2.text = description
Log.d(ContentValues.TAG, "-->arabic = $arabic")
Log.d(ContentValues.TAG, "-->latin = $latin")
Log.d(ContentValues.TAG, "-->translation = $translation")
Log.d(ContentValues.TAG, "-->description = $description")
}
I tried by replacing
val arabic = intent.getStringExtra("ARABIC_TEXT").toString()
also still it is returning null?
2021-07-22 22:31:16.411 9607-9607/com.example.yasiin D/ContentValues: -->arabic = null
2021-07-22 22:31:16.411 9607-9607/com.example.yasiin D/ContentValues: -->arabic = null
2021-07-22 22:31:16.411 9607-9607/com.example.yasiin D/ContentValues: -->latin = null
2021-07-22 22:31:16.411 9607-9607/com.example.yasiin D/ContentValues: -->translation = null
2021-07-22 22:31:16.411 9607-9607/com.example.yasiin D/ContentValues: -->description = null
Try replacing this
intent.putExtra("ARABIC_TEXT", strContentArabic?.get(position))
intent.putExtra("LATIN_TEXT", strContentLatin!![position])
intent.putExtra("TRANSLATION_TEXT", strContentTranslation!![position])
intent.putExtra("DESCRIPTION_TEXT", strContentDescription!![position])
With this
intent.putExtra("ARABIC_TEXT", strContentArabic)
intent.putExtra("LATIN_TEXT", strContentLatin)
intent.putExtra("TRANSLATION_TEXT", strContentTranslation)
intent.putExtra("DESCRIPTION_TEXT", strContentDescription)
You have already have the string, just put it in the extras.
Please just try the below line of code to update and check in your PrayerActivity, for this you can create one interface callback and call interface method(varargs with multiple params or string or pojo class) from adapter class where you are opening intent currently, then from PrayerActivity activity you can open it
val intent = Intent(this#PrayerActivity, PrayerReadActivity::class.java)
intent.putExtra("ARABIC_TEXT", strContentArabic?.get(position))
intent.putExtra("LATIN_TEXT", strContentLatin!![position])
intent.putExtra("TRANSLATION_TEXT", strContentTranslation!![position])
intent.putExtra("DESCRIPTION_TEXT", strContentDescription!![position])
startActivity(intent)
hope it may help you
I wanna pass some of informations of the selected item to be viewed in new activity AboutApp.kt, but here I test by one info only (name). I do not have any trouble with RecyclerView, it works. I've seen many ways to do parcelable ArrayList object but feeling confuse where activity to be implemented, so it's getting error in MainActivity and AboutApp (destination intent).
A piece code MainActivity.kt getting error in showSelectedHerbal, when I use position to putExtra
class MainActivity : AppCompatActivity() {
private lateinit var rvHerbal: RecyclerView
private var list: ArrayList<Herbal> = arrayListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvHerbal = findViewById(R.id.rv_herbal)
rvHerbal.setHasFixedSize(true)
list.addAll(HerbalData.listData)
showRecyclerList()
}
private fun showRecyclerList() {
rvHerbal.layoutManager = LinearLayoutManager(this)
val listHerbalAdapter = ListHerbalAdapter(list)
rvHerbal.adapter = listHerbalAdapter
listHerbalAdapter.setOnItemClickCallback(object : ListHerbalAdapter.OnItemClickCallback {
override fun onItemClicked(data: Herbal) {
showSelectedHerbal(data)
}
})
}
........
private fun showSelectedHerbal(data: Herbal) {
val moveIntent = Intent(this, AboutApp::class.java)
moveIntent.putExtra("Example_Item", list!![position])
this.startActivity(moveIntent)
}
.......
}
A piece code from AboutApp.kt that getting error in herbalName(). I know that I haven't implemented the parcelable so it's wrong
val intent = intent
val herbalData: HerbalData = intent.getParcelableExtra("Example_Item")
val title: String = herbalData.herbalName()
val itemName = findViewById<TextView>(R.id.item_name)
itemName.text = title
I'm so sorry, I attach you some of activities that I confuse may be one of them is the right place to be implement parcelable. Here is my data class Herbal.kt
data class Herbal(
var name: String = "",
var detail: String = "",
var photo: Int = 0
)
A piece code of the object HerbalData.kt
object HerbalData {
private val herbalName = arrayOf("Cengkeh",
"Ginseng",
"Jahe")
..........
val listData: ArrayList<Herbal>
get() {
val list = arrayListOf<Herbal>()
for (position in herbalName.indices) {
val herbal = Herbal()
herbal.name = herbalName[position]
herbal.detail = herbalDetail[position]
herbal.photo = herbalImage[position]
list.add(herbal)
}
return list
}
}
Help me please where activity to be write the parcelable ArrayList and how to fix it. Thanks in advance for any help.
First of all the error in your AboutApp.kt is because you have herbalName private in your HerbalData object. Remove the private modifier to access it there.
Just add #Parcelize annotation over your data class to automatically generate writeToParcel and createFromParcel methods for you!
#Parcelize
data class Herbal(...) : Parcelable
Add this in your build.gradle file:
androidExtensions {
features = ["parcelize"]
}
PS: Reference: https://medium.com/#BladeCoder/a-study-of-the-parcelize-feature-from-kotlin-android-extensions-59a5adcd5909
I recommend you read this.
You just have to make the Herbal class Parcelable.
data class Herbal(
var name: String = "",
var detail: String = "",
var photo: Int = 0
) : Parcelable {
companion object {
#JvmField
val CREATOR = object : Parcelable.Creator<Herbal> {
override fun createFromParcel(parcel: Parcel) = Herbal(parcel)
override fun newArray(size: Int) = arrayOfNulls<Herbal>(size)
}
}
private constructor(parcel: Parcel) : this(
name = parcel.readString(),
detail = parcel.readString(),
photo = parcel.readInt(),
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeString(detail)
parcel.writeInt(photo)
}
override fun describeContents() = 0
}
I am trying to pass two strings from AddNote to MainActivity. But it keeps getting null.
Unable to start activity (MainActivity)
java.lang.IllegalStateException: callingIntent.getStringExtra("intentTitle") must not be null
class MainActivity : AppCompatActivity() {
private val notes = arrayListOf<Note>()
private val db by lazy {
Room.databaseBuilder(this
,NoteDatabase::class.java
,"NoteDatabase.db")
.allowMainThreadQueries()
.build() }
lateinit var adapter: adapter
lateinit var title: String
lateinit var content: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
notes.addAll(db.dao().getNotes())
AddNote.setOnClickListener {
val i = Intent(this#MainActivity,AddNote::class.java)
startActivity(i)
}
// startActivity(Intent(this, AddNote::class.java))
val callingIntent = intent
title = callingIntent.getStringExtra("intentTitle")
content = callingIntent.getStringExtra("intentContent")
val note = Note(title,content)
val id = db.dao().insert(note)
note.id = id.toInt()
notes.add(note)
adapter = adapter(notes, db)
rootView.layoutManager = LinearLayoutManager(this)
rootView.adapter = adapter
}
override fun onResume() {
super.onResume()
notes.clear()
notes.addAll(db.dao().getNotes())
adapter.notifyDataSetChanged()
}
}
class AddNote : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_note)
var intentTitle = "Title"
var intentContent = "Content"
saveNote.setOnClickListener {
intentTitle = addTitle.text.toString()
intentContent = addContent.text.toString()
}
val i = Intent()
i.putExtra("title",intentTitle)
i.putExtra("content",intentContent)
startActivity(i)
}
}
You must start activity like this...
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", value)
startActivity(intent)
You must put the code that starts MainActivity inside saveNote.setOnClickListener:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_note)
var intentTitle = "Title"
var intentContent = "Content"
saveNote.setOnClickListener {
intentTitle = addTitle.text.toString()
intentContent = addContent.text.toString()
val i = Intent(this, MainActivity::class.java)
i.putExtra("title",intentTitle)
i.putExtra("content",intentContent)
startActivity(i)
}
}
The way your code worked was to start MainActivity as soon as AddNote activity was loaded, so I'm not sure what you are trying to do.