I am displaying list of check-boxes in horizontal RecyclerView.
It display values such as {"Rd" , "Gr" , "Yl"} but when user selects any of this value it should return {"RED" , "GREEN" , "YELLOW")
How can I bind these two value that show and return differently?
I am taking display values from R.string-arry
I created another string-array of actual values, and when user checked any of checkboxes I get that ID and replaced it with actual values.
For e.g. If user has selected "Gr" I get ID=1 then replaced with actual string-array
But this only works when code-color and original-color are in order. In my app I sometimes use Red,green,blue or sometimes green,yellow,blue. So, this won't help me.
From what I understood, you need a mapping between GR and Green, RD and Red etc.
You can try using a Hashmap.
HashMap<String,String> colourMap = new HashMap<>();
colourMap.put("GR","GREEN");
colourMap.put("RD","RED");
And then you can retrieve the respective value for your colour code:
String colour = colourMap.get("GR");
You can use a HashMap which will bind the two arrays as key value pair
public HashMap<String,String> bindColors() {
HashMap<String,String> map = new HashMap<>();
int length = orginalColors.length;
for (int i = 0; i < length; i++) {
map.put(orginalColors[i], codeColors[i]);
}
return map;
}
And for getting the Colors in code.
HashMap<String, String> keyPair = bindColors();
orginalColorsNewArray = keyPair.keySet().toArray(new String[keyPair.keySet().size()]);
codeColorsNewArray = keyPair.values().toArray(new String[keyPair.values().size()]);
or use .get() function
keyPair.get("YELLOW")
Now it will be easier for you to access the codes by id/position
Hope this helps.
Related
I have copied some code from a project and want to reuse a small part of it in my private app.
The class contains a Sparse Array
public class GolfResult {
String hcpAfter;
String hcpBefore;
SparseArray roundResults;
public GolfResult() {
hcpAfter = "";
hcpBefore = "";
roundResults = new SparseArray();
}
}
I have created an ArrayList for roundResults that is filled with the necessary data.
Then I am trying to fill the instance with content.
GolfResult golferRes = new GolfResult();
SparseArray<RoundResults> hu= new SparseArray<>();
hu = roundresults; // *
golferRes.setHcpAfter("33");
golferRes.setHcpBefore("kk");
golferRes.setRoundResults(hu);
But the problem is that hu = roudresults is not possible, because of the error message:
required: Android.util.SparseArray found: java.util.Array List
Any help will be welcome.
After receiving two helpful answers I got a step further, but now I am facing the problem that my SparseArray hu is empty {}.
The content of hu should be the class roundresults that has the following structure:
public class RoundResults {
boolean actualRound;
private List<HoleResult> holeResults;
Integer roundId;
Integer roundNumber;
String unfinishedReason;
The arrayList roundresults has the size of 1 and has data in the objects.
unfinishedReason =""
holeResults = ArrayLIST size= 18
roundID = "1"
roundNumber = "1"
actualRound = true
hu ={}
mValues = All elements are null
mSize = 0
Does anybody have an idea why?
SparseArray is different than ArrayList, from the documentation:
SparseArrays map integers to Objects. Unlike a normal array of
Objects, there can be gaps in the indices. It is intended to be more
memory efficient than using a HashMap to map Integers to Objects, both
because it avoids auto-boxing keys and its data structure doesn't rely
on an extra entry object for each mapping.
It's using a key value pair principle where the key is an integer and the value which the key mapping is the object. You need to use put [(int key, E value)](https://developer.android.com/reference/android/util/SparseArray.html#put(int, E)) where the E is your object. Remember that:
Adds a mapping from the specified key to the specified value,
replacing the previous mapping from the specified key if there was
one.
So you need to use a loop to add each object in your ArrayList as #valentino-s says:
SparseArray<RoundResults> hu= new SparseArray<>();
for( int i = 0; i < roundresults.size(); i++) {
// i as the key for the object.
hu.put(i, roundresults.get(i));
}
If I understand well your problem, maybe you can try with this:
for ( int i=0; i<roundresults.size(); i++ ) {
hu.put(i,roundresults.get(i));
}
After some trial and error I found a solution for the empty hu:
Instead of put I used append and it is working now.
hu.append(i, roundresults.get(i));
Time for a beer.
i have two ArrayLists:
List<String> names = new ArrayList<String>(10);
List<Drawable> drawables = new ArrayList<Drawable>(10);
which i want to sort alphabetically.
For this i created a TreeMap:
Map<List<String>, List<Drawable>> myMapToSort = new TreeMap<List<String>, List<Drawable>>();
myMapToSort.put(names, drawables);
First two Question
Is the map now sorted in lexicographical order? Or do i Need to do something additional?
After i have sorted them, if they are yet, i want to split them back again to List<String> and List<Drawable>. And i tried like this:
List<String> sortedNames = new ArrayList<String>(myMapToSort.keySet());
Of course it doesn't work because myMapToSort.keySet() Returns a Set and not List.
And List doesn't have an Constructor for a Set.
So how can i accomplish that and what i'm misunderstanding?
Any help is appreciated. Thanks in advance!
I figured it out by my own.
The key was to create a TreeMap with not two list but two single Objects:
Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>;
Then add the Items from the Arraylists one by one to the Map:
for(int i = 0; i<names.size(); i++) {
myTreeMap.put(names.get(i), drawables.get(i));
}
Now the Map is automatically sorted Lexicographical in relation with the Drawables.
That means Names and Drawables are sorted in lexicographical order.
If you want to retrieve the keys and the values and put them back in seperate ArrayLists simply type:
List <String> mySortedNames = new ArrayList<String>(myTreeMap.keySet());
List <Drawables> mySortedDrawables = new ArrayList<Drawables>(myTreeMap.values());
That's it. ;)
You can use SortedSet (or SortedList) to have sorted elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time.
For splitting a Map in two lists :
List<String> sortedNames = new ArrayList<String>();
List<Drawable> drawables = new ArrayList<Drawable>();
for (Map.Entry<String, Drawable> entry : map.entrySet())
{
sortedNames.add(entry.getKey()
drawables.add(entry.getValue());
}
I'm trying to implement an expandable listview with data coming from a database. I've already tried having the data added within the codes and it works so I'm now trying to have dynamic data from the database populate the listview.
The data is grouped in two, the main category and the member. For example if the main category is fruit, it's members may include mango, avocado, apples, etc. If animals, it may have horses, eagle, shark. The data always comes in pairs such as Animal, Horses; Animal, Eagle; Fruit, Apples. The expandable listview should appear as:
Animal
-- Horses
-- Eagle
Fruit
-- Apples
My code below can already determine the main group so the headers already display the main groupings of Fruit and Animal. By using
group_member.put(family_name, member_name);
I linked the member to the main category. My problem now is how to code for the iteration to group the members to the main category. So far I've already tried using iterator based on the sample codes given here in stackoverflow and from other sites however only the last elements of each group is display. I've also tried using the for-each loop bur still no success.
String json = jsonParser.makeHttpRequest(URL_COMPONENTS, "POST", params);
JSONArray components = null;
ArrayList<HashMap<String, String>> componentList;
List<String> main_group = new ArrayList<String>();
HashMap<String, String> group_member = new HashMap<String, String>();
try {
components = new JSONArray(json);
if (components != null) {
for (int i = 0; i < components.length(); i++) {
JSONObject c = components.getJSONObject(i);
String family_name = c.getString(TAG_FAMILY_NAME);
String member_name = c.getString(TAG_MEMBER_NAME);
main_group.add(family_name);
group_member.put(family_name, member_name);
if (!listDataHeader.contains(main_group))
listDataHeader.add(main_group);
componentList.add(group_member);
}
}
}
Please help. Thanks in advance!
If you're using HashMap you can't have a key more than once in your list. Each key must be unique.
This could be a solution:
HashMap<String, ArrayList<String>> group_member = new HashMap<String, ArrayList<String>>();
... using the Hashmap as a directory and the key is returning an Arraylist of the family members.
I have to create an app in android with a database.In that database I have a predefined list of products.
Now,the thing is that my ap has to offer to the user the posibility to introduce in that list some other products which are not in the list.
To this end, I've created an autocomplete text view in which I introduce a new product and I take the text fro autocomplete and I have to write it in the database
Now,my problem is that when I display the products that I've introduced in the database,the toast text that I use to display what I have in the database it shows me nothing next to "product......".
Now,that may be because when I try to get the text from the autocomplete I get nothing in return?
This is how I read from autocomplete:
mItem = (AutoCompleteTextView) findViewById(R.id.todo_edit_item);
String nou=mItem.getText().toString();
And then I compare nou(which is what I wrote in the autocomplete) with what I have predefnied in the list,so if it is a new product(which was not in the list already) the I add it in the database:
for(int i = 0; i < l; i++)
{
if (nou!=fruits[i])
t=true;
else t=false;
}
if (t==true)
{
db.insertTitle(nou);
fruits=db.getAllfromDB("Fruits","fruit");
l=l+1;
}
Anyone any ideas of what I'm doing wrong in here cause I can't figure out.I'lll be here for further details.Thank u in advance:)
You compare strings using != instead of using !nou.equals(fruits[i]). also you compare to all elements in array each time, since you so t is always the value of the comparison to the last element in the array whether a match was found or not.
It should be written like that:
t = true;
for(int i = 0; i < l; i++)
{
if (nou.equals(fruits[i]))
{
t=false;
break;
}
}
if (t==true)
{
db.insertTitle(nou);
fruits=db.getAllfromDB("Fruits","fruit");
l=l+1;
}
I have an Android application which retrieves from a external server, a name and a corresponding ID (this could be 1 name and ID combo or multiple name ID combinations), these are all stored in a HashMap<String, String> - The ID as the key and the Name as the value.
What I then would like to implement is a dynamic Spinner that populates itself with the 'Names' from this HashMap and when the user selects one of these names a setting somewhere I set to the ID number. This ID number will then be used in later server requests.
My question is what is the best way to implement this custom Spinner from the HashMap so that when the option is selected the ID number is set somewhere. This ID number has to be accessible from several activities - the spinner is present in several different activities... but should have the same effect on each screen.
Design patterns and pseudo code would be hugely appreciated. At the moment the Spinner is on 2 different screens, at the top below the ActionBar, but obviously the code is in both XML layout files.
Cheers.
EDIT
Code to set names and IDs in HashMap:
// Returns a Map of blog name to blog ID associated with the authenticated user
public Map<String, String> extractBlogInfo(XMLDataExtracter blogData)
{
Log.d(TAG, "BlogOperations::extractBlogInfo()");
ArrayList<String> blogIDs = new ArrayList<String>();
ArrayList<String> blogNames = new ArrayList<String>();
Map<String, String> blogIDNamePairs = new HashMap<String, String>();
// Get ID and Names and store them in blogIDs and blogNames variables
if (blogIDs.size() == blogNames.size())
{
for(int i = 0; i < blogIDs.size(); i++)
{
blogIDNamePairs.put(blogIDs.get(i), blogNames.get(i));
}
}
else
{
// An error occured
Log.d(TAG,
"BlogOperations::extractBlogInfo() > An error occured - ID and Name array sizes do not match");
return null;
}
return blogIDNamePairs;
}
For this you can use Shared preference.. You get the Id of the selected value from spinner and stored it in shared preference..
So that you can access this value any where inside your Apps..
If you want to display the selected spinner value from Say Activity1 in Activity2 get the value from Shared preference, now it will be Id so get the corresponding Name from the Id in hash Map..
For shared preference take a look at this... and this....