Defus
Defus

Reputation: 829

Android random string generator

I have a problem. I want to draw a random String something like this aXcFg3s2. What i doing bad ? How change my random()

private String random;
private String charsEntered;
private EditText et;
private Button ok;
CaptchaInterface.OnCorrectListener mCorrectListener;

public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
    mCorrectListener = listener;
}

public TextCaptcha(Context context) {
    super(context);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}

public static String random() {
    Random generator = new Random();
    String x = (String) (generator.nextInt(96) + 32);
    return x;
}

public void onCreate(Bundle icicle) {
    setContentView(R.layout.main);
    random = random();
    TextView display = (TextView) findViewById(R.id.textView1);
    display.setText("Random Number: " + random); // Show the random number
    et = (EditText) findViewById(R.id.etNumbers);
    ok = (Button) findViewById(R.id.button1);
    ok.setOnClickListener(this);

}

public void onClick(View arg0) {
    // TODO Auto-generated method stub
    try {
        charsEntered = et.getText().toString();
    } catch (NumberFormatException nfe) {
        Toast.makeText(et.getContext(), "Bla bla bla",
                Toast.LENGTH_LONG).show();
    }

    if (random == charsEntered) {
        Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
    }
}

Upvotes: 47

Views: 103996

Answers (11)

Sumit Ojha
Sumit Ojha

Reputation: 444

 private fun getRandomHexString(numchars: Int): String? {
    val r = Random()
    val sb = StringBuffer()
    while (sb.length < numchars) {
        sb.append(Integer.toHexString(r.nextInt()))
    }
    return sb.toString().substring(0, numchars)
}

Upvotes: 1

Mussa Charles
Mussa Charles

Reputation: 849

You can simply convert current time (in millis) to string such as

import java.util.Calendar;

String newRandomId = String.valueOf(Calendar.getInstance().getTimeInMillis());

Or

String newRandomId = Calendar.getInstance().getTimeInMillis() + "";

//Eg: output: "1602791949543"

Upvotes: 0

BitByteDog
BitByteDog

Reputation: 3484

Quick one liner using the org.apache.commons.lang3.RandomStringUtils package.

String randonString = RandomStringUtils.randomAlphanumeric(16);

Requires the library dependency in the gradle build file:

implementation 'org.apache.commons:commons-text:1.6'

Upvotes: 0

Aryan Moradi
Aryan Moradi

Reputation: 134

This function run in kotlin ->

fun randomString(stringLength: Int): String {
    val list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()
    var randomS = ""
    for (i in 1..stringLength) {
        randomS += list[getRandomNumber(0, list.size - 1)]
    }
    return randomS
}

fun getRandomNumber(min: Int, max: Int): Int {
   return Random().nextInt((max - min) + 1) + min
}

Or you can use my library https://github.com/Aryan-mor/Utils-Library

Upvotes: 2

android developer
android developer

Reputation: 116322

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()
}

Upvotes: 82

Hardik Lakhani
Hardik Lakhani

Reputation: 1544

You can simply use the following method to generate random String with 5 character and it will return arrayList of random String

public ArrayList<String> generateRandomString() {

    ArrayList<String> list = new ArrayList<>();
    Random rnd = new Random();
    String str = "";

    String randomLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String randomLetterSmall = "abcdefghijklmnopqrstuvwxyz";

    for (int n = 0; n < 50; n++) {
        str = String.valueOf(randomLetters.charAt(rnd.nextInt(randomLetters.length())));

        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));

        //Copy above line to increase character of the String
        list.add(str);
    }
    Collections.sort(list);
    return list;
}

Upvotes: 1

शु-Bham
शु-Bham

Reputation: 952

You need to import UUID. Here is the code

import java.util.UUID;

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

Upvotes: 56

ORY
ORY

Reputation: 413

final  String[] Textlist = { "Text1", "Text2", "Text3"};

TextView yourTextView = (TextView)findViewById(R.id.yourTextView);

Random random = new Random();

String randomText = TextList[random.nextInt(TextList.length)];

yourTextView.setText(randomText);

Upvotes: 0

user3855135
user3855135

Reputation:

this is how i generate my random strings with desired characters and desired length

          char[] chars1 = "ABCDEF012GHIJKL345MNOPQR678STUVWXYZ9".toCharArray();
                                StringBuilder sb1 = new StringBuilder();
                                Random random1 = new Random();
                                for (int i = 0; i < 6; i++)
                                {
                                    char c1 = chars1[random1.nextInt(chars1.length)];
                                    sb1.append(c1);
                                }
                                String random_string = sb1.toString();  

Upvotes: 12

bennettaur
bennettaur

Reputation: 1253

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 ==

Upvotes: 60

LuxuryMode
LuxuryMode

Reputation: 33741

You cannot cast an int to a String. Try:

 Random generator = new Random();
 String x = String.valueOf (generator.nextInt(96) + 32);

Upvotes: 0

Related Questions