Android random string generator

There are a few things wrong with your code.

You cannot cast from an int to a string. Cast it to a char instead. This however will only give you a single char so instead you could generate a random number for the length of your string. Then run a for loop to generate random chars. You can define a StringBuilder as well and add the chars to that, then get your random string using the toString() method

example:

public static String random() {
    Random generator = new Random();
    StringBuilder randomStringBuilder = new StringBuilder();
    int randomLength = generator.nextInt(MAX_LENGTH);
    char tempChar;
    for (int i = 0; i < randomLength; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        randomStringBuilder.append(tempChar);
    }
    return randomStringBuilder.toString();
}

Also, you should use random.compareTo() rather than ==


the problem is that you've handled only a single character instead of using a loop.

you can create an array of characters which has all of the characters that you wish to allow to be in the random string , then in a loop take a random position from the array and add append it to a stringBuilder . in the end , convert the stringBuilder to a string.


EDIT: here's the simple algorithm i've suggested:

private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";

private static String getRandomString(final int sizeOfRandomString)
  {
  final Random random=new Random();
  final StringBuilder sb=new StringBuilder(sizeOfRandomString);
  for(int i=0;i<sizeOfRandomString;++i)
    sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
  return sb.toString();
  }

and on Kotlin:

companion object {
    private val ALLOWED_CHARACTERS = "0123456789qwertyuiopasdfghjklzxcvbnm"
}

private fun getRandomString(sizeOfRandomString: Int): String {
    val random = Random()
    val sb = StringBuilder(sizeOfRandomString)
    for (i in 0 until sizeOfRandomString)
        sb.append(ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)])
    return sb.toString()
}

You need to import UUID. Here is the code

import java.util.UUID;

id = UUID.randomUUID().toString();

Tags:

Android