Is it possible to pass intent into a button? - kotlin

I would like to know is it possible to pass an intent into the button? Because when I used the debug function, it is shown that the currentUser is null. Below are the codes that I tried to use.
R.id.goalsView ->{
intent = Intent(activity, GoalsActivity::class.java
var cUser : String? = activity!!.intent.getStringExtra("currentUser")
intent.putExtra("Current User", cUser)
startActivity(intent)
}
binding.btnView.setOnClickListener{
val intent = Intent(this, ViewGoalActivity::class.java)
var currentUser : String? = intent.getStringExtra("Current User")
intent.putExtra("Current User", currentUser)
startActivity(intent)
}

Related

Can I use the repeated binding data in the variable?

Please understand my poor English :)
Can I use it as follows?
before
if (binding.heightEditText.text.isNotBlank() && binding.weightEditText.text.isNotBlank()) {
val intent = Intent(this, ResultActivity::class.java).apply {
putExtra("weight", binding.weightEditText.text.toString().toFloat())
putExtra("height", binding.heightEditText.text.toString().toFloat())
}
startActivity(intent)
}
after
val height = binding.heightEditText.text
val weight = binding.weightEditText.text
if (height.isNotBlank() && weight.isNotBlank()) {
val intent = Intent(this, ResultActivity::class.java).apply {
putExtra("weight", weight.toString().toFloat())
putExtra("height", height.toString().toFloat())
}
startActivity(intent)
}
Yes, you can use this way to define those variables.
Just make sure your variables are in the same method that you are calling to retrieve the updated values into defined variables.
I'm updating minor things in your code.
val height = binding.heightEditText.text.toString()
val weight = binding.weightEditText.text.toString()
if (height.isNotBlank() && weight.isNotBlank()) {
val intent = Intent(this, ResultActivity::class.java).apply {
putExtra("weight", weight.toFloat())
putExtra("height", height.toFloat())
}
startActivity(intent)
}
I hope it's helpful to you!

lateinit property binding has not been initialized though i did not set it as lateinit

I faced that error when i was trying to update my views with new ViewBinding stuff. I don't define the value as "lateinit" but logccat says "lateinit property binding has not been initialized" why i m taking this ?
Thanks in advance.
The exception is on private val email and password rows.
class MainActivity : AppCompatActivity() {
private lateinit var auth : FirebaseAuth
private lateinit var binding: ActivityMainBinding
private val email = binding.emailText.text.toString()
private val password = binding.passwordText.text.toString()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
auth= FirebaseAuth.getInstance()
val guncelKullanici = auth.currentUser
if (guncelKullanici!= null) {
val intent = Intent(this, haber_akisi::class.java)
startActivity(intent)
finish()
}
}
fun girisYap ( view: View) {
if (email.isNotBlank() && password.isNotBlank()) {
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val intent = Intent(this,haber_akisi::class.java)
startActivity(intent)
finish()
}
}.addOnFailureListener { exception ->
Toast.makeText(this,exception.localizedMessage,Toast.LENGTH_LONG).show()
}}else {
Toast.makeText(this,"Lütfen E-mail ve Password alanlarını doldurunuz",Toast.LENGTH_LONG).show()
}
}
fun kayitOl ( view : View) {
if ( email.isNotBlank() && password.isNotBlank() ) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val intent = Intent(this, haber_akisi::class.java)
startActivity(intent)
finish()
}
}.addOnFailureListener { exception ->
Toast.makeText(this, exception.localizedMessage, Toast.LENGTH_LONG).show()
}
}else {
Toast.makeText(this,"Lütfen E-mail ve Password alanlarını doldurunuz",Toast.LENGTH_LONG).show()
}
}
}
This is because private val email = binding.emailText.text.toString() is using the "binding" variable before it has been initialized. The error is saying that the "lateinit var binding" has not been initialized yet but you are accessing it on private val email = binding.emailText.text.toString()
Edit: One way to solve this is to make email and password as lateinit vars too. Another way is to not have an email and password class level properties and just access the binding where it's needed like in girisYap() and kayitOl()
You are accessing binding(ActivityMainBinding Identifier) in the next lines, after its declaration.
You need to initialize binding before using it.

Realtime database not stored data

l cant save data Firebase realtime database no error code. auth create user but database not stored user data inside app. l change database rules
{
"rules": {
".read": true,
".write": true
}
}
l close firewall , try to test another app,I deleted the application completely from firebase and re-created it and downloaded the google-services.json file again. but can't solve problem.I tried a lot of different code structures, none of them worked this is my signup activity code block last version
class SignUpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.sign_up_activity)
signInView.setOnClickListener {
startActivity(Intent(this, SignInActivity::class.java))
}
sign_up_btn.setOnClickListener {
createAccount()
}
}
private fun createAccount() {
val fullname = fullNameSignUp.text.toString()
val username = userNameSignUp.text.toString()
val email = emailSignUp.text.toString()
val password = passwordSignUp.text.toString()
when{
TextUtils.isEmpty(fullname) -> Toast.makeText(this,"full name is required.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(username) -> Toast.makeText(this,"user name is required.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(email) -> Toast.makeText(this,"email is required.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(password) -> Toast.makeText(this,"password is required.", Toast.LENGTH_LONG).show()
else -> {
/*
val alert = AlertDialog.Builder(this)
alert.setTitle("SignUp")
alert.setMessage("Please wait, this may take a while...")
alert.setCancelable(false)
alert.show()
*/
val progressDialog = ProgressDialog(this#SignUpActivity)
progressDialog.setTitle("SignUp")
progressDialog.setMessage("Please wait, this may take a while...")
progressDialog.setCanceledOnTouchOutside(false)
progressDialog.show()
val mAuth: FirebaseAuth = FirebaseAuth.getInstance()
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
saveUserInfo(fullname, username, email,progressDialog)
progressDialog.dismiss()
// AlertDialog.Builder(this)
// finish()
} else {
val message = task.exception!!.toString()
Toast.makeText(this, "Error: $message", Toast.LENGTH_LONG).show()
mAuth.signOut()
progressDialog.dismiss()
// AlertDialog.Builder(this)
// finish()
}
}
}
}
}
private fun saveUserInfo(fullname: String, username: String, email: String,progressDialog:ProgressDialog) {
val currentUserID = FirebaseAuth.getInstance().currentUser!!.uid
val usersRef = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String,Any>()
userMap["uid"] = currentUserID
userMap["fullname"] = fullname
userMap["username"] = username
userMap["email"] = email
userMap["bio"] = ""
userMap["image"] = "gs://fart-me-ae78f.appSpot.com/Default Images/profile.png"
// db = FirebaseFirestore.getInstance()
// val usersRef = db.collection("Users").add(userMap)
// usersRef.addOnCompleteListener { task ->
usersRef.child("Users").child(currentUserID).setValue(userMap)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Account has been created successfully.", Toast.LENGTH_LONG).show()
progressDialog.dismiss()
val intent = Intent(this#SignUpActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
// AlertDialog.Builder(this)
// finish()
} else {
val message = task.exception!!.toString()
Toast.makeText(this, "Error: $message", Toast.LENGTH_LONG).show()
FirebaseAuth.getInstance().signOut()
progressDialog.dismiss()
//AlertDialog.Builder(this)
// finish()
}
}
}
}
The solutions found by those with the same problem did not work for me. I would be glad if anyone can help me solve this problem

Kotlin for android - first button works, second doesn't?

im trying to code a really simple app, it's my first one for android.
In the console i don't get any error messages but when i try to run the app on android emulator i can only press the first button and get to the activity i want, second doenst work. Maybe you can help me.
Thats my code:
val button = findViewById<Button>(Btn)
button.setOnClickListener {
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
val button = findViewById<Button>(Btn2)
button.setOnClickListener {
val intent = Intent(this, MainActivity3::class.java)
startActivity(intent)
}
}
}
}
What am i missing? Thank you in adavance!
After startActivity(intent) you need a "}"
If you write it this way, you can only press the BTN button first before the second btn2 button is set and can be clicked later, so you should write the btn2 code logic outside, like this
val button = findViewById<Button>(Btn)
button.setOnClickListener {
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
}
val button = findViewById<Button>(Btn2)
button.setOnClickListener {
val intent = Intent(this, MainActivity3::class.java)
startActivity(intent)
}
I see that you've got the answer from community, I'll join))
Move the second button's logic outta first one.
val button = findViewById<Button>(Btn1)
button.setOnClickListener {
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
}
val button = findViewById<Button>(Btn2)
button.setOnClickListener {
val intent = Intent(this, MainActivity3::class.java)
startActivity(intent)
}
Hope, findViewById method soon will be deprecated.
val button = findViewById<Button>(Btn)
button.setOnClickListener {
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
}
val button = findViewById<Button>(Btn2)
button.setOnClickListener {
val intent = Intent(this, MainActivity3::class.java)
startActivity(intent)
}
You are defining the second button and setting the Listener to it inside the listener of the first button
val button = findViewById<Button>(Btn)
button.setOnClickListener {
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
}
val button2 = findViewById<Button>(Btn2)
button2.setOnClickListener {
val intent = Intent(this, MainActivity3::class.java)
startActivity(intent)
}

Kotlin code Send SMS from within App without using default app

I am trying to build an app whereby the user clicks a submit button which will send the contents of their input via SMS to a predefined number. Being very new to Kotlin, I have been helped with the code to send the data via SMS, however it opens up the default messaging app and the user has to interact with the messaging app and then navigate back to my app. What I would like is for this to happen in the background and send directly from my app. The code is below...Any help greatly appreciated, Many thanks
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val backbut = findViewById<Button>(R.id.backbut)
backbut.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
var spinner: Spinner? = null
spinner = this.spinner
val sub1: Button = findViewById<Button>(R.id.sub1)
sub1.setOnClickListener {
val cust: String = cust.text.toString()
val reg: String = reg.text.toString()
val pal: String = pal.text.toString()
val cont:String = cont.text.toString()
val data: String =
"CUSTOMER : ".plus(cust).plus("\n").plus("CONTAINER : ").plus(cont).plus("\n").plus("VEH
REG : ").plus(reg).plus("\n").plus("PALLETS : ")
.plus(pal)
startActivity(getSendSmsIntent("1234567", data))
}
}
// textview_selected!!.text = "Selected : "+ Spinner [position]
private fun getSendSmsIntent(phoneNumber: String, content: String?): Intent? {
val uri = Uri.parse("smsto:$phoneNumber")
val intent = Intent(Intent.ACTION_SENDTO, uri)
intent.putExtra("sms_body", content)
return getIntent(intent, true)
}
private fun getIntent(intent: Intent, isNewTask: Boolean): Intent? {
return if (isNewTask) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) else intent
}
}
After reading the documentation, I think you can achieve your needs using the following code :
private fun sendSMS(phoneNumber: String, message: String) {
val sentPI: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("SMS_SENT"), 0)
SmsManager.getDefault().sendTextMessage(phoneNumber, null, message, sentPI, null)
}
Add this permission to your AndroidManifest and make sure it's granted :
<uses-permission android:name="android.permission.SEND_SMS" />
Call sendSMS method as follows :
sendSMS("+2126000000", "Some text here")
Screenshot :