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);
Related
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
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.
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
}
I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);
I have an Arraylist of HashMap. Each HashMap element contains two columns: column name and corresponding value. This HashMap will be added into a ListView with 3 TextView.
I populate the ArrayList as follows, and then assign that to an adapter in order to display it:
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
.
Now on listItemClick, the fetched data is of the different form at different time.
For eg. My list contains following data:
ABC 123 1
PQR 456 4
XYZ 789 7
i.e. When I log the fetched string after clicking 1st list item, I get one of the several outputs:
{1=ABC ,2=123 ,3=1}
{First=ABC ,Second=123 ,Third=1}
{1=123 ,0=ABC ,2=1}
and even
{27=123 ,28=1 ,26=ABC}
Initially I used:
int pos1 = item.indexOf("1=");
int pos2 = item.indexOf("2=");
int pos3 = item.indexOf("3=");
String symbol = item.substring(pos1 + 2,pos1 - 2).trim();
String current = item.substring(pos2 + 2, pos3 - 2).trim();
String change = item.substring(pos3 + 2, item.length() - 1).trim();
Then for the 4th case, I have to use:
int pos1 = item.indexOf("26=");
int pos2 = item.indexOf("27=");
int pos3 = item.indexOf("28=");
String symbol = item.substring(pos1 + 3, item.length() - 1).trim();
String current = item.substring(pos2 + 3, pos3 - 3).trim();
String change = item.substring(pos3 + 3, pos1 - 3).trim();
So that I get ABC in symbol and so on.
But, by this approach, application loses it's reliability completely.
I also tried
while (myVeryOwnIterator.hasNext()) {
key = (String) myVeryOwnIterator.next();
value[ind] = (String) addList1.get(key);
}
But it's not giving proper value. Instead it returns random symbol for eg. ABC or PQR or XYZ.
Am I doing anything wrong?
Thanks in advance!
The HashMap's put function does not insert value in specific order. So the best way is to put the keyset of the HashMap in a ArrayList and use the ArrayList index in retrieving the value
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
ArrayList<String> listKeySet;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
listKeySet.add(COLUMN1);
listKeySet.add(COLUMN2);
listKeySet.add(COLUMN3);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
And when retrieving use
addList1.get(listKeySet.get(position));
Here, the arraylist listKeySet is just used to preserve the order in which the HashMap keys are inserted. When you put data in HashMap insert the key into the ArrayList.
I don't think using HashMap for this purpose is a good idea. I would implement Class incapsulating your data like
class myData {
public String Column1;
public String Column2;
public String Column3;
// better idea would be making these fields private and using
// getters/setters, but just for the sake of example these fields
// are left public
public myData(String col1, String col2, String col3){
Column1 = col1;
Column2 = col2;
Column3 = col3;
}
}
and use it like
ArrayList<myData> list1 = new ArrayList<myData>();
for (int i = 0; i < count; i++) {
list1.add(new myData(symbol[i], current[i], change[i]));
}
//no need to create new adapter on each iteration, btw
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
You will need to make changes in your adapter to use myData instead of HashMap<String,String>, of course.