Weird output on edit text with alert Dialog - kotlin

Weird output
I'm getting this output on my alert dialog when I enter text.
Can someone maybe explain why this is happening.
No errors in logcat.
Here is my code for the Alert Dialog
private fun declineDialogBox() {
val dialogBuilder = AlertDialog.Builder(this)
val inflater = layoutInflater
val dialogLayout = inflater.inflate(R.layout.alert_dialog, null)
val toBeCorrected = dialogLayout.findViewById<EditText>(R.id.editText)
dialogBuilder.setMessage("Reason is?")
.setCancelable(false)
.setPositiveButton("Proceed") { dialog, id ->
finish()
Toast.makeText(applicationContext, "Reason is $toBeCorrected", Toast.LENGTH_SHORT)
.show()
}
.setNegativeButton("Cancel") { dialog, id ->
}
val alert = dialogBuilder.create()
alert.setView(dialogLayout)
alert.setTitle("To Be Corrected")
alert.show()
}

You are printing the instance of EditText instead the value, add .text to get the value from EditText
Toast.makeText(applicationContext, "Reason is ${toBeCorrected.text}", Toast.LENGTH_SHORT).show()

Related

Issues related to moving to MainActivity by pressing a button

If the user presses the positive button, they want to move it to MainActivity
fun setPositiveButtonClick(callback: (() -> Unit)?, view: View? = null) {
val intent = Intent(this#ErrorDialog, MainActivity::class.java)
startActivity(intent)
var view = view
if (view == null) view = this.view
this.positiveCallback = callback
view?.let { v ->
v.yes.setOnClickListener {
callback?.let { c ->
c()
}
dismiss()
}
}
}
Here is the error
I'm assuming this is in some sort of Dialog class, so I think you simply need to get the context of it by just replacing
val intent = Intent(this#ErrorDialog, MainActivity::class.java)
to
val intent = Intent(this.context, MainActivity::class.java)

How should write the findViewById pass data to Fragment page from Activity page using kotlin

This is my activity page:
override fun receiveDetections(detections: Detector.Detections) {
val barcodes = detections.detectedItems
if (barcodes.size() == 1) {
scannedValue = barcodes.valueAt(0).rawValue
runOnUiThread {
cameraSource.stop()
toastText = scannedValue
Toast.makeText(this#InsertStockInActivity, toastText, Toast.LENGTH_SHORT).show()
val i = Intent(this#InsertStockInActivity, InputStockInActivity::class.java)
i.putExtra("key", toastText)
startActivity(i)
finish()
}
}else
{
Toast.makeText(this#InsertStockInActivity, "value- else", Toast.LENGTH_SHORT).show()
}
}
This is my Fragment Page, I using requireActivity().getIntent(), how can I show the "key" data?
val value = requireActivity().intent.getStringExtra("key") ?: ""
binding.edtId.findViewById<EditText>(R.id.value)
The binding.edtId.find.......... it got error, how should I write for this line ?

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 :

LocalDate.format causes OutofBount Exception in Observer

I'm making an app in android using Kotlin, Material Design Components and the new architecture components.
I have an activity that starts a DialogFragment onCreate
The fragment has 6 Views that, via an observer, observe a different LiveDate for each and every one.
While checking all the this setup work I noticed that after 7 view switching I get
2020-05-12 20:43:19.346 4778-4778/package E/InputEventReceiver: Exception dispatching input event.
2020-05-12 20:43:19.346 4778-4778/package E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2020-05-12 20:43:19.357 4778-4778/package E/MessageQueue-JNI:
java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
at android.text.Layout$HorizontalMeasurementProvider.get(Layout.java:1589)
...
I cheked the following things:
did all the setup on only one view -> still crashes
did all the setup on only one view but without using the "createDateFieldObserver" method -> still carshes
not calling the observer -> no crash
calling the observer but without the LocalDate.format -> no crash
I concluded the probleme is in the format function but I do not understand why.
The error is not pointing in that direction.
Any ideas?
Activity code
class UITestingActivity: FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_greenhouse)
val dialog = LabTimesDialogFragment()
dialog.show(supportFragmentManager, "LabTimes")
}
}
Fragment Code
class TimesDialogFragment : DialogFragment() {
companion object Companion {
private val TAG: String = "TimesDialog"
}
private val datesViewModel: TimesViewModel by activityViewModels()
private lateinit var datesViews: Map<LiveData<LocalDate>, TextInputEditText>
override fun onCreateDialog(savedInstanceState: Bundle?) : Dialog {
val viewsArray: Array<TextInputEditText>
return activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
val rootView: View = inflater.inflate(R.layout.dialog_filter_times, null)
builder.setView(rootView)
.setPositiveButton(R.string.feed) { dialog, id -> closeDialog() }
.setNegativeButton(R.string.cancel) { dialog, id -> getDialog()?.cancel() }
val dialog: AlertDialog = builder.create()
val fromSampling: TextInputEditText = rootView.findViewById(R.id.from_sampling) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val toSampling: TextInputEditText = rootView.findViewById(R.id.to_sampling) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val fromSending: TextInputEditText = rootView.findViewById(R.id.from_sending) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val toSending: TextInputEditText = rootView.findViewById(R.id.to_sending) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val fromReceiving: TextInputEditText = rootView.findViewById(R.id.from_receiving) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val toReceiving: TextInputEditText = rootView.findViewById(R.id.to_receiving) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
datesViews = mapOf(datesViewModel.fromSampling to fromSampling,
datesViewModel.toSampling to toSampling,
datesViewModel.fromSending to fromSending,
datesViewModel.toSending to toSending,
datesViewModel.fromReceiving to fromReceiving,
datesViewModel.toReceiving to toReceiving
)
for ((liveData, textView) in datesViews) {
liveData.observe(this, createDateFieldObserver(textView))
textView.setOnClickListener { v ->
Log.d(TAG, "hello"+v.id)
}
}
return dialog
} ?: throw IllegalStateException("Activity cannot be null")
}
private fun closeDialog() {
// save dates to ViewModel
// closeDialog
TODO()
}
private fun createDateFieldObserver(tw: TextInputEditText): Observer<LocalDate> {
return Observer { date ->
Log.d(TAG, "obs"+tw.id)
tw.setText(date.format(DateTimeFormatter.ISO_DATE))
//tw.setText("hello")
}
}
}
ViewModel
class TimesViewModel : ViewModel() {
val fromSampling: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val toSampling: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val fromSending: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val toSending: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val fromReceiving: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val toReceiving: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
}
it has been a while since I programmed for android. Everything I'm using here is new to me so if you spot an anti-pattern in this little code I would be glad to know.
Tnx
Turns out it was because of the layout.
There was no enough room in the view to display the whole date.
I don't understand why it causes indexoutofbound but the solution is to simply make the view "wrap_content" or bigger