I have a basic survey app that emails results upon hitting the submit button at the end. In the string that is built it calls the result of the checked radio button to put into the email, but it's showing as an integer instead of the button text.
Currently:
val id = group1.checkedRadioButtonId
returns 213120809 or 2131230810 depending on which response is checked
I've tried to add getString() to it so like so:
val id = group1.checkedRadioButtonId.getString()
but that doesn't seem to do anything. Does anyone know if there's another command I should be using? This is in Kotlin.
There is no property to get selected button text.
You can get it like this
val radioButtonText = when (group1.checkedRadioButtonId) {
R.id.radioButton1 -> radioButton1.text
else -> radioButton2.text
}
Related
On a Fragment for user logging, I have two EditText widgets - one for email and the other for password. When the user has saved its credentials via SharedPreferences, then these are obtained to fill the input fields programmatically via setText() like this:
// obtain the credentials
val email : String? = loginFragmentViewModel.retrieveEmailFromSharedPreferences()
val password: String ? = loginFragmentViewModel.retrivePasswordFromSharedPreferences()
email?.let { emailString->
password?.let{ pw ->
// fill the EditText inputs programmatically
binding.apply{
loginEmail.setText(emailString)
loginPassword.setText(pw)
}
// validate the input data
loginFragmentViewModel.loginDataChanged(
binding.loginEmail.text.toString(),
binding.loginPassword.text.toString()
)
}
}
The loginDataChanged() method is implemented on the ViewModel side. It validates the given inputs (here: email & password). Here the relevant parts:
private val _loginState = MutableLiveData<LoginFormState>()
val loginFormState : LiveData<LoginFormState> = _loginState
fun loginDataChanged(email: String, password: String){
if(!isEmailValid(email)){
_loginState.value = LoginFormState(emailError = R.string.invalid_email)
}
else if(!isPasswordValid(password)){
_loginState.value = LoginFormState(passwordError = R.string.invalid_password)
}
else{
_loginState.value = LoginFormState(isDataValid = true)
}
}
As you can see, based on the validation result, we update the LiveData variable which leads us back to the LoginFragment side:
// listen for type errors made by the user during the login
loginFormState.observe(viewLifecycleOwner, Observer { loginFormState ->
...
...
// notify the user that the given email is wrong
loginFormState.emailError?.let{
binding.loginEmail.error = getString(it)
}
// notify the user that the given password is wrong
loginFormState.passwordError?.let{
binding.loginPassword.error = getString(it)
}
})
As you can see, when there is any error with an input, I let the user know about via the error property of EditText widget. They show an exclamation mark, notifying the user that the input is not correct.
What my problem is:
But that does not work when the inputs are set programmatically like you have seen above. After setting them like this, you can still see the exclamation mark on the right side of the EditText widgets ALTHOUGH the given email and password are correct. When the correct email and password are obtained from SharedPreferences and the EditText fields are filled, then it still looks like as they are wrong. But they are not.
So, how can I solve this problem?
Note: I obtain the SharedPreferences so that the user does not have to re-type them.
I am working on an android application that shows bar specials in the area and I want to make sure the only users that are using our app are 21+ years old. I have created a login/registration activity using edit texts and the information typed into the edit texts is sent to a mySQL database.
I have already searched for tutorials on youtube/stack overflow/google for help on this and I have only found datepicker tutorials. I am not sure how I would implement a datepicker tutorial into my project using edit texts.
Here is part of my RegisterActivity.java file that I want to validate the data when the user clicks on register. I have already figured out how to validate email/password but do not know how to add date difference into my code. I have also added my submitForm function that is called....
I am not sure what the output is supposed to look like or how to implement age validation into my project as a I am still fairly new to using Android Studio and I am open to new ideas etc. on how to best implement this into my project.
Here is part of my RegisterActivity.java file that I want to validate the data when the user clicks on register. I have already figured out how to validate email/password but do not know how to add date difference into my code. I have also added my submitForm function that is called....
buttonSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = signupInputEmail.getText().toString();
String password = signupInputPassword.getText().toString();
if (password.length()< 8){
signupInputPassword.setError("Your password must be at least 8 characters");
}else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
signupInputEmail.setError("You must enter a valid email address");
} else {
submitForm();
}
}
});
submitForm()
private void submitForm() {
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
String gender;
if(selectedId == R.id.female_radio_btn)
gender = "Female";
else
gender = "Male";
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
gender,
signup_input_DOB.getText().toString());
}
Looks like you are following a long way to do this task. You can simply use DatePicker (Android Date Picker Official Docs
and set the selection range for the date, set the selected date (by the user) on the TextView. User Interface for handling the click event.
Create Interface.
public interface IOnItemClickListenerCountryStates {
void onAgeClick(String Date);
}
Convert the date of birth on the sign up input from String to Date like this:
String DOB = signup_input_DOB.getText().toString();
Date dateOfBirth=new SimpleDateFormat("dd/MM/yyyy").parse(DOB);
Then pass the date of birth to a method computing for the age:
int age = currentDate.getYear() - dateOfBirth.getYear();
I was looking for my problem on the internet, but the solutions given still do not work.
How to transfer data from first Activity to second?(plain text)
MainActivity
btn.setOnClickListener {
val player1= findViewById<EditText>(R.id.et1) as EditText
val player2= findViewById<EditText>(R.id.et2) as EditText
val intent1= Intent(this, MainActivity3::class.java).apply {
putExtra("player1",player1.getText().toString())
putExtra("player2",player2.getText().toString())
}
startActivity(intent1)
}
Second Activity
fun PlayGame(cellID:Int,buSelected:Button){
val playe1= intent.getStringExtra(EXTRA_MESSAGE)
val playe2= intent.getStringExtra(EXTRA_MESSAGE)
val textView2= findViewById<TextView>(R.id.textView2).apply{
text= playe1
text=playe2
}
if(ActivePlayer==1){
textView2.setText(": $playe1")
buSelected.text="0"
buSelected.setBackgroundResource(R.color.blue)
player1.add(cellID)
ActivePlayer=2
}else{
textView2.setText(": $playe2")
buSelected.text="X"
buSelected.setBackgroundResource(R.color.green)
player2.add(cellID)
ActivePlayer=1
}
buSelected.isEnabled=false
CheckWiner()
}
I want the player's name from MainActivity goes to Second ;p
The problem is in the way you get your values. Try this:
val playe1= intent.getStringExtra("player1")
val playe2= intent.getStringExtra("player2")
Use a sharedpreferences, in your next activity after saving the values to a Val or var delete the shared preferences continue.
It’s not ideal but it just may get you to where you can at least interact with that data.
I used this method for something similar last night. If I have time tonight I was going to post a how to on this on my website. If I can I’ll swing by here and edit my answer. With code and explanation unless you get it figured out by then.
Hello this is my first app with kotlin i am trying to make annual rate calculation app the problem is i have 4 activities every activity own button and edit's texts
i wan't when The User click the button, the program get the numbers from Edit's texts and only make the calculation and save it somewhere and same work for the activity 2 and 3.
but when he click the last button of the last activity i want to call all the results and show it in ViewText
The Question is:How to save data Every time somewhere and call when i need it?
First Activity
class st {
var int_P: Double? = null
var ctl_P: Double? = null
public constructor(int_P: Any, ctl_P: Any) {
this.int_P = int_P.toString().toDouble() //Physique
this.ctl_P = ctl_P.toString().toDouble()
public fun GetMP(): Double {
return (this.int_P!! + (this.ctl_P!! * 2)) / 3
}
}
Btn_Next1.setOnClickListener ({
var int_P = java.lang.Double.parseDouble(edit_IP.text.toString()) //Physique
var ctl_P = java.lang.Double.parseDouble(edit_CP.text.toString())
var ss = st(int_P,ctl_P)
val ic = Intent(this, Sec_Act::class.java)
startActivity(ic)
})
(Secend and Third Activity Same)
Activity 4
btn1.setOnClickListener ({
var act1 = MainActivity.st().GetMC()
Textv.text = act1.toString()
})
With this method i got problem (no value passed for parameter int_P , ctl_P)
There are many different ways to send information back to an Activity:
onActivityResult(),
having a singleton class,
use Shared Preferences,
headless fragments,
sqlite database,
store the information in a file.
Intents
receivers
You need to determine which will be the best solution for you. Whether it's kotlin or java, the methodology will be the same.
Is it possible for the uiautomator to select a password EditText? I have no problem finding other EditText views by their android:hint property, but the uiautomatorviewer shows all password fields as NAF. I tried setting the password field content description and that didn't work either.
If it's not possible, how do you set a timeout for a tester to manually enter a password?
I had the same problem with API v16.
Today I tried my script with v17 (Android 4.2) and it worked like a charm.
It seems that the first version of uiautomator has some major bugs.
Here is my code:
// click the admin button
new UiObject(new UiSelector().text("admin")).click();
// set pwd text
new UiObject(new UiSelector().description("pwdEditText")).setText("admin");
// click login button
new UiObject(new UiSelector().description("loginButton")).click();
Sometimes, your Views won't have a ResourceId, such as the case where you need to programmatically type into a text field within a webpage rendered inside a WebView. i.e.
// Fetch the EditText within the iOrder Webpage.
final UiObject lUiObject = UiDevice.getInstance(getInstrumentation()).findObject(new UiSelector().className(EditText.class).textContains("Enter Loyalty Code"));
In such cases, we need to use the UiSelector class to dynamically search for the EditText; however, you'll find that the returned Matcher<View> isn't compatible with the onView(with(...)) methods.
When using the UiSelector, you can take advantage of a UiDevice reference to programmatically fake key presses using the approach below:
/* Declare the KeyCodeMap. */
private static final KeyCharacterMap MAP_KEYCODE = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
/** Simulates typing within a UiObject. The typed text is appended to the Object. */
private final void type(final UiObject pUiObject, final String pString, final boolean pIsSimulateTyping, final boolean pIsClearField) throws Exception {
// Fetch the Instrumentation.
final Instrumentation lInstrumentation = getInstrumentation();
// Fetch the UiDevice.
final UiDevice lUiDevice = UiDevice.getInstance(lInstrumentation);
// Are we clearing the Field beforehand?
if(pIsClearField) {
// Reset the Field Text.
pUiObject.setText("");
}
// Are we going to simulate mechanical typing?
if(pIsSimulateTyping) {
// Click the Field. (Implicitly open Android's Soft Keyboard.)
pUiObject.click();
// Fetch the KeyEvents.
final KeyEvent[] lKeyEvents = SignUpTest.MAP_KEYCODE.getEvents(pString.toCharArray());
// Delay.
lInstrumentation.waitForIdleSync();
// Iterate the KeyEvents.
for(final KeyEvent lKeyEvent : lKeyEvents) {
// Is the KeyEvent a Release. (The KeyEvents contain both down and up events, whereas `pressKeyCode` encapsulates both down and up. This conditional statement essentially decimates the array.)
if(lKeyEvent.getAction() == KeyEvent.ACTION_UP) {
// Press the KeyEvent's corresponding KeyCode (Take account for special characters).
lUiDevice.pressKeyCode(lKeyEvent.getKeyCode(), lKeyEvent.isShiftPressed() ? KeyEvent.META_SHIFT_ON : 0);
// Delay.
lInstrumentation.waitForIdleSync();
}
}
// Close the keyboard.
lUiDevice.pressBack();
}
else {
// Write the String.
pUiObject.setText(pUiObject.getText() + pString);
}
// Delay.
lInstrumentation.waitForIdleSync();
}
I just find them by id:
onView(withId(R.id.input_password)).perform(typeText("password"));
I see that the UI Automator Viewer now also shows the resource-id property, which would be useful if you don't have access to the code.