How to get a random value from a string array without repetition? - android

How to get a random value from a string array in android without repetition?
I have array in String.xml file as below -
<string-array name="msg">
<item>Cow</item>
<item>Pig</item>
<item>Bird</item>
<item>Sheep</item>
</string-array>
I am selecting random string by using following code -
String[] array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
String Msg = array[new Random().nextInt(array.length)];
Can anyone help me please? Thanks is advance...!

Can you just do something like this:
Collections.shuffle(copyOfArray);
Then loop through that?
for (int i = 0; i < copyOfArray.size(); i++) {
println(copyOfArray.get(i))
}

try this -
array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
//String msg = array[new Random().nextInt(array.length)];
LinkedList<String> myList = new LinkedList<String>();
for (String i : array)
myList.add(i);
Collections.shuffle(myList);
for (int i = 0; i < myList.size(); i++) {
String msg=myList.get(i);
}

Try this solution,
LinkedList<String> myList = new LinkedList<String>();
String[] words = { "Cow", "Pig", "Bird", "Sheep" };
for (String i : words)
myList.add(i);
Collections.shuffle(myList);
Then,
sampleText.setText(myList.pollLast());
pollLast() in LinkedList will retrieves and removes the last element of this list, or returns null if this list is empty.

try this.
int max = array.length() - 1;
int min = 0;
String Msg = array[new Random().nextInt(max - min + 1) + min];

First convert your String resource array to ArrayList
Fill value from current ArrayList to HashSet and convert that HashSet to newly ArrayList
Now shuffle that new ArrayList

Related

Split strings on string array

i have String Array like this:
String[] q1={"AAA-BBB","AAA-CCC","AAA-DDD"}
and i want result like this
temp={"BBB","CCC","DDD"}
i tried below code but the result is wrong
for(int i=0;i<q1.length;i++){
ArrayList<String> temp=new ArrayList<>(Arrays.asList(q1[i].split("AAA-")));
}
Try like this:
ArrayList<String> temp=new ArrayList<>();
for(int i=0;i<q1.length;i++){
String[] array = q1[i].split("-");
temp.add(array[1]);
}
You could use substring:
ArrayList<String> temp = new ArrayList<>();
for(int i=0; i<q1.length; i++){
temp.add(q[i].substring(q[i].indexOf('-') + 1, q[i].length()))
}
you find error Because you use split
Splits this string around matches of the given regular expression.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
q1[i].split("AAA-")
in this line you got 2 result splited 0 = "" AND 1 = "BBB"
so you need to pick the sec result
you have multi Solution
like https://stackoverflow.com/a/50234408/6998825 said
String[] array = q1[i].split("-");
temp.add(array[1]);
//change this q1[i].split("AAA-") to
q1[0].substring(4)
if your AAA- is not going to change
Have you tried creating the ArrayList outside of the loop? As previously you were creating a new ArrayList for every element in your string array
ArrayList<String> temp = new ArrayList<>();
for(int i=0;i<q1.length;i++){
temp.add(q1[i].substring(4);
}
Assuming that "AAA-" is not going to change.

how to equate items in the string-array android

i have two String arrays mylist and listprice.
<string-array name="mylist">
<item>Bottle</item>
<item>Watch</item>
<item>Books</item>
<item>Mobile</item>
<item>Purse</item>
<item>Pen</item>
<item>Glass</item>
<item>Class</item>
<item>Rubber</item>
<item>Fan</item>
</string-array>
<string-array name="listprice">
<item>160</item>
<item>2600</item>
<item>200</item>
<item>26000</item>
<item>260</item>
<item>10</item>
<item>500</item>
<item>3000</item>
<item>3</item>
<item>380</item>
</string-array>
i want to initilize both the arrays items such that "bottle" equals "160","watch" equals "2600" and so on... how can i achieve it...thanks in advance...
You can use hash map for both array relation:
HashMap<String,String> map=new HashMap<String,String>();
for (int i = 0; i < getResources().getStringArray(R.array.mylist).length; i++) {
map.put(getResources().getStringArray(R.array.mylist)[i],getResources().getStringArray(R.array.listprice)[i]);
}
String[] itemList = getResources().getStringArray(R.array.mylist);
String[] itemPrice = getResources().getStringArray(R.array.listprice);
Now you can put all these in hashmap.
HashMap<String, String> items = new HashMap<>();
for(int i = 0; i<itemList.length; i++){
items.put(itemList[i], itemPrice[i]);
}
Now if you want to get price of Fan then just write
String price = items.get("Fan"); //it will be 380
OR you can make use of str.equals(str2) method for checking the item and then from the index getting the price from itemPrice array.
You can access string arrays with below code:
Resources res = getResources();
String[] mylist = res.getStringArray(R.array.mylist);
String[] listprice = res.getStringArray(R.array.listprice);
and you can use mylist[index] equals listprice[index]
Take two strings and concatinate the values .
private String[] concat(String[] A, String[] B) {
int aLen = A.length;
int bLen = B.length;
String[] C= new String[aLen+bLen];
System.arraycopy(A, 0, C, 0, aLen);
System.arraycopy(B, 0, C, aLen, bLen);
return C;
}
In java you can do something like with
String myList[]=getResources().getStringArray(R.array.mylist);
String myListPrice[]=getResources().getStringArray(R.array.listprice);
You can create a class lets say
public class ItemPrice{
private String listItemName;
private String listPrice;
public String getListItemName(){return listItemName;}
public String getListPrice(){return listPrice;}
public void setListItemName(String itemName){this.listItemName = itemName;}
public void setListPrice(String listPrice){this.listPrice = listPrice;}
}
Your array logic can be something like this
List<ItemPrice> itemPriceList = new ArrayList<ItemPrice>();
for(int i=0;i<myList.length;i++){
ItemPrice items = new ItemPrice();
items.setListItemName(myList[i]);
items.setListPrice(myListPrice[i]);
itemPriceList.add(items);
}
So you can get the itemPriceList which will contain both item along with its price encapsulated in one object. I am assuming both array length will be same and are mapped according to their index.
Do share if this is what you are looking for and if you require further help?
You can get your array like this:
String[] listprice = getResources().getStringArray(R.array.listprice);
String[] mylist = getResources().getStringArray(R.array.mylist);

Handle comma separated string

Creating an app in which i want to get string from json but i have one key and multiple value so i don't know how to handle this.
"colours": "#fff600,#000000,#ffffff,#00000,#ff9900,#333333"
And want to use this color in different class:
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new android.animation.ArgbEvaluator(), Color.RED, Color.BLUE,Color.WHITE,Color.YELLOW,Color.CYAN,Color.MAGENTA,Color.GREEN,Color.GRAY);
colorAnimation.setDuration(1400);
Put the value of colours in string variable and then split the string in following way and add it to an arraylist :
String[] arr = str.split(",");
ArrayList<String> arr1 = new ArrayList<String>();
for (int i=0; i<arr.length; i++){
arr1.add(arr[i]);
}
Get value of color and use string tokenizer with ',' delima like this:
StringTokenizer stringTokenizer = new StringTokenizer(colorValueString, ",");
Also it has stringTokenizer.nextToken to get the next color in string
You can get the value of colours as a string and then split the string into parts like this:
String colours = json.getString("colours");
Log.d(TAG, colours);
String items[] = colours.split(",");
for (String item : items) {
Log.d(TAG, item);
}
If you own the json
You should use JSONArray:
"colours": ["#fff600","#000000","#ffffff","#00000","#ff9900","#333333"]
And read it like
JSONObject json = ...;
JSONArray colorsArray = json.getJSONArray("colours");
for(int i = 0; i < colorsArray.length(); i++) {
String colorString = colorsArray.getString(i);
int color = Color.parseColor(colorString);
// you should probably also catch IllegalArgumentException for wrong input
}
If you don't own the json
You can read it as string and split around commas:
JSONObject json = ...;
String colorsString = json.getString("colours");
String[] colorStrings = colorsString.split(",");
for(String string : colorStrings) {
int color = Color.parseColor(string);
// you should probably also catch IllegalArgumentException for wrong input
}

How to pass edit text values to integer array in Android

I'm a beginner in Android.
I have created a edit text field where can I enter values from 0-9. Now, I have to get these values in an integer array.
example : entered values are 12345.
I need an array containing these values
int[] array = {1,2,3,4,5};
I need to know the way to do this. Kindly help.
Try this :
String str = edittext.getText.toString();
int length = str.length();
int[] arr = new int[length];
for(int i=0;i<length;i++) {
arr[i] = Character.getNumericValue(str.charAt(i));
}
You can use something like this:
int[] array = new int[yourString.length()];
for (int i = 0; i < yourString.length(); i++){
array[i] = Character.getNumericValue(yourString.charAt(i));
}

Compare a value with all the values in arraylist in java

In my case Arraylist contains user define timings like{12:23,15:40,17:17...}.
how can i print message when system time is equal to user timings.
First make an array for this by below code
String s = "{12:23,15:40,17:17...}";
String newstring = s.replace("{").replace("}");
int size = StringUtils.countOccurrencesOf(newstring , ",");
String[] arrayString = new String[size];
Now Compare
for(int i=0; i<size; i++){
if(yoursystemtime.equals(newstring.split(",")[i])){
Toast.makeText(context, "equal", Toast.Lenght.Short).show();
}
}

Categories

Resources