I triying make a android app for learning but my buttons clickable only once. I can't click second time. Here is my codes for button.
There is the xml codes:
<Button
android:id="@ id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:width="200dp"
android:height="80dp"
android:shadowColor="@color/red"
android:text="@string/button"
android:textColor="@color/black"
android:textSize="20sp"
android:visibility="visible"
app:cornerRadius="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/text"
app:rippleColor="@color/red"
app:strokeColor="@color/red"
tools:ignore="TextContrastCheck" />
And there is java codes:
buttonGenerate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
passwordText.setText(generate());
}
});
There is generate method:
private String generate () {
Random random = new Random();
int character;
while (password.length() < 16) {
character = random.nextInt(76);
password = characters[character];
}
return password;
There is variables:
private final String[] characters = {
"A" , "B" , "C" , "D" , "E" , "F" , "G" , "H",
"I" , "J" , "K" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" ,
"U" , "V" , "W" , "X" , "Y" , "Z", "a" , "b" , "c" , "d" , "e" , "f" , "g" , "h",
"i" , "j" , "k" , "l" , "m" , "n" , "o" , "p" , "q" , "r" , "s" , "t" ,"u" , "v" , "w" , "x" , "y" , "z", "0" , "1" , "2" , "3" , "4" , "5" , "6" ,
"7" , "8" , "9", "!" , "#" , "'" , " " , "%" , "(" , ")" , "&" ,
"=" , "?" , "*" , "-" , "$" , "{" , "}" };
private String password = "";
CodePudding user response:
After calling generate() the first time password.length() < 16
will always be false.
Put String password
inside generate():
private String generate () {
String password = "";
Random random = new Random();
int character;
while (password.length() < 16) {
character = random.nextInt(76);
password = characters[character];
}
return password;}
CodePudding user response:
It seems that you generate() function generating the same string on every click, correct your generate() function.
Modify generate() function like this for create random password and pass argument length which you want for password.
fun generate(length: Int) : String {
val allowedChars = ('A'..'Z') ('a'..'z') ('0'..'9')
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}