How do you generate a string which has a user defined length? - android

I need to be able to generate strings with a user defined length.
For example, if the user enters 128, I need a string with 128 characters.
Any ideas on how to accomplish this?

You can create X random chars (in a loop) and use a StringBuffer to concatenate them

static final String generate(int n) {
final char[] buf = new char[n];
final Random rand = new Random();
final int n_cs = Character.MAX_VALUE + 1;
while (n > 0) {
char ch;
do {
ch = (char) rand.nextInt(n_cs);
} while (Character.isHighSurrogate(ch)
|| Character.isLowSurrogate(ch));
buf[--n] = ch;
}
return new String(buf);
}
Generally, you should probably specify some sort of alphabet, as follows...
static final String generate(int n, final char[] alphabet) {
final char[] buf = new char[n];
final Random rand = new Random();
final int n_alpha = alphabet.length;
while (n > 0) {
buf[--n] = alphabet[rand.nextInt(n_alpha)];
}
return new String(buf);
}

Related

when i try to get the unicode of emoji, why i got some unicode like de01, de02, de03?

img description: first one was textview to get unicode; second one was textview to restore emoji; last one was edittext to input text or emoji
and post my code below
String s = emojiconEditText.getText().toString();
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder1 = new StringBuilder();
private void testTwo(String s, StringBuilder stringBuilder, StringBuilder stringBuilder1, TextView emojiconText, TextView emojiconText2) {
int codePointCount = s.codePointCount(0, s.length() - 1);
for (int i = 0; i <codePointCount ; i++) {
int letterCodePoint = s.codePointAt(i);
int type = Character.getType(letterCodePoint);
if (type==Character.SURROGATE||type==Character.OTHER_SYMBOL){
stringBuilder.append("[emoji]U+"+Integer.toHexString(letterCodePoint)+"[emoji]");
}else{
stringBuilder.append(s.charAt(i));
}
}
String text = stringBuilder.toString();
emojiconText.setText(text);
String[] emojis = text.split("\\[emoji\\]");
for (int i = 0; i <emojis.length ; i++) {
if (emojis[i].contains("U+")){
// String[] subSplit = emojis[i].split("[/emoji]");
// int deccode = Integer.parseInt(subSplit[0], 16);
String substring = emojis[i].substring(2, emojis[i].length() );
int deccode = Integer.parseInt(
substring, 16);
/* stringBuilder1.append("\\u");
stringBuilder1.append( deccode);*/
stringBuilder1.append(new String(Character.toChars(deccode))+" ");
}else{
stringBuilder1.append(emojis[i]);
}
}
emojiconText2.setText(stringBuilder1.toString());
}

how to get random audio file from raw array on android?

This is my array, in the form of audio files
int[] rawQuetion = {R.raw.alikhlas, R.raw.alkafirun};// this for question
int [] rawAnswer={R.raw.jwbaliklas,R.raw.alfalaq };// this for answer
and this method to randomize questions
//fisher-yates Shuffle
public void playSoal() {
shuffleArray(rawQuetion);
try{
int idx = new Random().nextInt(rawQuetion.length);
mp = MediaPlayer.create(this, rawQuetion[idx]);
mp.start();
}
static void shuffleArray(int[] arr)
{
Random rnd = new Random();
for (int i = arr.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Swap
int a = arr[index];
arr[index] = arr[i];
arr[i] = a;
}
}
public void audioFile() throws IOException{
InputStream is = getResources().openRawResource(R.raw.jwbaliklas);// I want get audio file from rawAnswer based rawQuestion
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
in = new BufferedInputStream(is);
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
out.flush();
byte[] audioBytes = out.toByteArray();
for (int i = 0; i < audioBytes.length; i++) {
audioBytes[i] = (byte) ((audioBytes[i]) & 0xFF); }
absNormalizedSignal = hitungFFT(audioBytes);
AppLog.logString("===== INI DARI AUDIO FILE");
}
public void audioFile() throws IOException{
InputStream is = getResources().openRawResource(R.raw.jwbaliklas);// I want get audio file from rawAnswer based rawQuestion
You have your answer right here: use openRawResource() to open a raw resource. You don't need to hard-code specific argument values in your code. The method takes an int argument. How you determine the value to pass it entirely up to you. For example, you can declare your audioFile() method to take an integer argument and pass that on to openRawResource():
public void audioFile(final int resid) throws IOException{
InputStream is = getResources().openRawResource(resid);
Then, where you have your corresponding question/answer audio ids, you can pass the correct id.

How to covert String to byte for BLE mBluetoothGatt.writeCharacteristic?

I am developing in Android BLE.
I try to send string to BLE device(like TI CC2541) , and it seems can not send string direct to BLE device.
It need to convert the String to Byte.
I have search some information , there has someone use URLEncoder.encode.
But I am not sure which is the answer what I need.
But how to convert the String to Byte?
The following code is writeCharacteristic for BLE
public void writeString(String text) {
// TODO Auto-generated method stub
BluetoothGattService HelloService = mBluetoothGatt.getService(HELLO_SERVICE_UUID);
BluetoothGattCharacteristic StringCharacteristic = HelloService.getCharacteristic(UUID_HELLO_CHARACTERISTIC_WRITE_STRING);
mBluetoothGatt.setCharacteristicNotification(StringCharacteristic , true);
int A = Integer.parseInt(text);
//How to convert the String to Byte here and set the Byte to setValue ?????
StringCharacteristic .setValue(A, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
mBluetoothGatt.writeCharacteristic(StringCharacteristic );
Log.d(TAG, "StepCount Characteristic End!");
}
How to convert the String to Byte?
Where you get your String:
byte[] strBytes = text.getBytes();
byte[] bytes = context.yourmWriteCharacteristic.getValue();
Please add a null check too like:
if (bytes == null) {
Log.w("Cannot get Values from mWriteCharacteristic.");
dismiss();// equivalent action
}
if (bytes.length <= strBytes.length) {
for(int i = 0; i < bytes.length; i++) {
bytes[i] = strBytes[i];
}
} else {
for (int i = 0; i < strBytes.length; i++) {
bytes[i] = strBytes[i];
}
}
Now, something like:
StepCount_Characteristic.setValue(bytes);
mBluetoothGatt.writeCharacteristic(StepCount_Characteristic);
I found the following code help me convert the string.
private byte[] parseHex(String hexString) {
hexString = hexString.replaceAll("\\s", "").toUpperCase();
String filtered = new String();
for(int i = 0; i != hexString.length(); ++i) {
if (hexVal(hexString.charAt(i)) != -1)
filtered += hexString.charAt(i);
}
if (filtered.length() % 2 != 0) {
char last = filtered.charAt(filtered.length() - 1);
filtered = filtered.substring(0, filtered.length() - 1) + '0' + last;
}
return hexStringToByteArray(filtered);
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
private int hexVal(char ch) {
return Character.digit(ch, 16);
}
If you want to convert string value. you just need to call like the following:
String text;
byte[] value = parseHex(text);

Check if next char in a string is a space

I would like to check if the current char is a blank space as i dont want to change that. So i would like to change all the letters like i do now, but keep the spaces.
e.g. "that man" with C = 2 should become "vjcv ocp".
thanks in advance :)
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
C = Integer.valueOf(ceasarNr);
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);
}
Just skip the iteration if the character is a space:
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
//Skip if it is space.
if chars[i-1] == ' ';
continue;
C = Integer.valueOf(ceasarNr);
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);
}
There is method for checking if char is blank space ->
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
C = Integer.valueOf(ceasarNr);
if(!Character.isWhitespace(chars.charAt(i-1)) {
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);

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();
}
}
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()
}
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 ==
You need to import UUID.
Here is the code
import java.util.UUID;
id = UUID.randomUUID().toString();
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();
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
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;
}
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)
}
You cannot cast an int to a String. Try:
Random generator = new Random();
String x = String.valueOf (generator.nextInt(96) + 32);
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);
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'
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"

Categories

Resources