How to perform addition operation using the hash map - android

HASH MAP
How to perform the addition when an hash map getting an input from the user
through the Edit text in android
final HashMap map = new HashMap<>();
map.put("input1", data1.getText().toString());
map.put("input2", data2.getText().toString());
map.put("input3", data3.getText().toString());
and i want to store and view the value in textview

I Didn't Get What you want
You have to convert that into Integers usingInteger.parseInt(data(x).getText.toString())
You can use HashMap.get() method
Do it with your own logic
I Guess It is Like this:
Integer Sum = ((map.get("input1")) + (map.get("input2")) + (map.get("input3")))

Related

Hashmap put the same value

I just want to ask why my HashMap is inserting the same value even if I put it inside a loop?
val parentMap = HashMap<String, Any?>()
val map = HashMap<String, Any?>()
orders.forEachIndexed { i, order ->
map["id"] = order.id
map["productName"] = order.productName
map["quantity"] = order.quantity
Log.i(TAG, "order=$order")
parentMap["data$i"] = map
Log.i(TAG, "map=$parentMap") // This parent map contains a same value from map...
}
Log.i(TAG, "map=$parentMap")
Did I forget something to put??
Any help is appreciated, Thanks.
So what you are doing here is assigning the map object to your parent map. The parent map stores the map object as a whole instead of the data. You will have to create a new 'map' object in every iteration.
I think "map" can be a reference variable. so it will insert the same values
To sum up what everyone said here.
In java and kotlin all objects stored in a heap and all your variables only store references to the objects in heap:
When you are doing this: parentMap["data$i"] = map
Your keys, ex: data1, data2, data3... will point to an instance of the same map which you created here: val map = HashMap<String, Any?>().
So everything that you do to your map:
map["id"] = order.id
map["productName"] = order.productName
map["quantity"] = order.quantity
change only one map that you have.
To fix it you can put your map creation inside the loop.
Or I suggest you to use immutable style like:
orders.mapIndexed { i, order ->
"data$i" to mapOf(
"id" to order.id,
"productName" to order.productName,
"quantity" to order.quantity
)
}.toMap()
You are creating the Map object outside the loop.
val map = HashMap()
So it will create single map entry where as you need different map for parent map.
Now you are entering different values in your map but since all maps references are now pointing to same Map Object so all Maps in your parent map will be showing last entries made to map.
The Solution is to keep val map = Hashmap() inside the loop. So with each iteration a different map objects will be created containg different data as per the iterations.

Android - Is it possible to have a lookup array?

I know there's an answer to this, but i'm not sure what to search and cannot remember the right phrasing.
Essentially what i mean, i'm being passed an integer. I want to search through an array using this integer to return a string value.
E.g.
I'm given the number 2. My lookup array looks like so:
array.add(1, "Auckland")
array.add(2, "Wellington")
array.add(3, "Bay of Plenty")
When i iterate through the array, i want to return "Wellington".
Can someone point me in the right direction please? :)
Hi you should declare a HashMap of Integer String:
HashMap<Integer, String> map= new HashMap<Integer, String>();
map.put(1, "Auckland");
map.put(2, "Wellington");
map.put(3, "Bay of Plenty");
And then to get the String you should call the HashMap using the key:
String yourString = map.get(1);

How to update a key's value in an ArrayList<HashMap<String,String>> in Android?

I am trying to compare and update an item in a ArrayList<HashMap<String,String>>named cart.
I am doing the following:
cart_list.put("quantity", "" +5); //cart_list is HashMap<String,String>
cart_list.put("item_id", "" + 1);
cart.add(cart_list);
cart_list.put("quantity", "" +6); //cart_list is HashMap<String,String>
cart_list.put("item_id", "" + 1);
cart_list.put("prefernces", "no salt");
cart.add(cart_list);
I want to update the 'preferencesfromno salttoxtra salt`. Can anyone tell me step by step how to do it?
You need to get your appropriate HashMap from your list
Map<String,String> map = cart.get(n);
where n is the index of the HashMap in your list (remember the first list will be index 0), so if you wanted the first HashMap in your list, you'd do
Map<String,String> map = cart.get(0);
Then, you can simply overwrite the previous value, since a key (e.g. prefernces) can only map to one value, this will overwrite the previous value.
map.put("prefernces", "xtra salt");
Note that your keys have to exactly match, and in your code you've used "prefernces" and then in your comments you use "preferences", which are different spellings.

Eliminating range key criteria for Dynamo Update query?

How can I get Dynamo's UpdateItemRequest to either ignore the range key, or do a coarse test such as not null?
I am using a range key which contains the time of a record update. Separately, I update rows which I select using an ID field which is not a key. I update the ID field using an expectedAttribute in an UpdateItemRequest. Dynamo's UpdateItemRequest forces me to specify a range key value. My ID update code will not know the range key value. Can I somehow not specify a range key and not get an error? Or can I provide a simple range key test like not null?
When I remove the range key, AWS throws an error, "The provided key element does not match the schema"
// construct the update map
HashMap<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
AttributeValue av = new AttributeValue().withN("1");
AttributeValueUpdate avu = new AttributeValueUpdate().withValue(av).withAction(AttributeAction.PUT);
updates.put("Column1", avu);
AttributeValue av2 = new AttributeValue().withN("2");
AttributeValueUpdate avu2 = new AttributeValueUpdate().withValue(av2).withAction(
AttributeAction.PUT);
updates.put("Column2", avu2);
// construct the key map
HashMap<String, AttributeValue> keyMap = new HashMap<String, AttributeValue>();
AttributeValue hashValue = new AttributeValue().withN("10");
keyMap.put("hashKey", hashValue);
AttributeValue lastModKeyValue = new AttributeValue().withN("1404175127074");
// ****** I want to remove this key but Dynamo throws an error
keyMap.put("problemRangeKey", lastModKeyValue);
// expected value comparison
AttributeValue idValue = new AttributeValue().withN("100");
ExpectedAttributeValue expected = new ExpectedAttributeValue(idValue);
UpdateItemRequest request = new UpdateItemRequest().withTableName(DatabaseConstants.CHART_TABLE)
.withKey(keyMap).withAttributeUpdates(updates).addExpectedEntry(ID, expected);
ddb.updateItem(request);
For clarity, here is how I use the range key to find rows after a specific time. If I remove this time range, then I would do a big scan every time to find rows after a specific time.
Map keyConditions = new HashMap();
AttributeValue attribute = new AttributeValue().withN("10");
Condition hashKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString())
.withAttributeValueList(attribute);
keyConditions.put("hashKey", hashKeyCondition);
// specify new records
long lastQueryTime = PrefsActivity.getLastDynamoQueryTime(activity);
String lastTimeString = String.valueOf(lastQueryTime);
Log.v(TAG, "get Charts from dynamo that are after " + lastTimeString);
// update the query time to now
long now = System.currentTimeMillis();
PrefsActivity.setLastDynamoQueryTime(activity, now);
AttributeValue timeAttribute = new AttributeValue().withN(lastTimeString);
Condition timeCondition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
.withAttributeValueList(timeAttribute);
keyConditions.put("problemRangeKey", timeCondition);
List<Map<String, AttributeValue>> ChartsInMaps = new ArrayList<Map<String, AttributeValue>>();
Map lastEvaluatedKey = null;
QueryRequest request = new QueryRequest().withTableName("tableName")
.withKeyConditions(keyConditions).withExclusiveStartKey(lastEvaluatedKey);
QueryResult result = ddb.query(request);
I'm working with the latest AWS Android SDK. In the sample above, I'm setting the hashKey to "10". In practice, that will vary.
Thanks in advance for any help!
Jeff
The question is, you want to update all items with a specific hashKey value and a specific column value (column name is id).
The table is Hash-Range schema. Since you don't know the range key, you have to fetch all the rows with that hashKey and then do a filter based on the column value (ID == value). You can use query filter to do that efficiently. Then for each row in your query, do a conditional put with expected value (ID == value) just to be sure.
QueryRequest request = new QueryRequest();
// set up query request (table name, etc)
// set up query filter (ID == value)
QueryResponse response = client.query(request)
for (item in response.items):
PutItemRequest req = new PutItemRequest();
// set up put item request
// set up primary key for item to update
// hashkey = item.hashkey
// rangekey = item.rangeKey
// set up expected value (ID == value)
client.updateItem(req)
On the other hand, since you want to efficiently query all the rows after a specific time, you can create a Local Secondary Index with "time" as a range key instead of making "time" the range key of your base table. You can still do efficient query using LSI (compared with scanning the table and filter by time). Whats more important is, if your "ID" attribute can uniquely identify a row with your hashkey, you can make "ID" the range key of your base table. This way you can also update the item efficiently since you already know the hashkey value and range key value (id value).
Of course it only truly benefits you when your hashkey and "ID" can uniquely identify a row :)

Android - Get single String value using HashMap

In my application, I've preloaded Spinner with ArrayList.The ArrayList contains multiple Text String. These text Strings will serve as message template user can select from spinner. Also I want these String keyword might be replaced with variable when message is being sent. Like "Text" will be replaced with EditText content, "Phone No " replaced with Sender's no, "Date" replaced with Message Date
I have tried to search on HashMap in Android, but getting problem:
HashMap<String, String> template=new HashMap<String, String>();
template.put("Text", editText.getText().toString());
template.put("Phone No",senderPhone);
template.put("Date",receivedDate);
now I want to display it as Single string like Text, Phone No, Date. can this String be editable.
You can use
StringBuilder builder = new StringBuilder();
for (String name : template.values())
{
builder.append(name + " ");
}
String templateString = builder.toString();
This will get all the values from the HashMap using the values() and concat it into a String
To get a value from Hashmap, use:
String Text = (String)template.get("Text");
String phoneNo= (String)template.get("PhoneNo");
String date = (String)template.get("Date");
You can combine all the above 3 and display it where ever you want to
For Example,
String displayString = Text + "-" + phoneNo + " -" + date
editText.setText(displayString);
This edit text by default would be editable until and unless you make it non editable.!
EDIT: (Refer comments for purpose of Edit)
(1) Set the edit text value as the value selected by user from spinner.
editText.setText(displayString);
(2) After user selects and modifies the edittext, let the user click a confirm button.
(3) In confirm button code, add the value to your local storage (IF REQUIRED!).
(4) Refresh the spinner to include this modified value
To refresh, if you want to modify the existing list in spinner then refer Refresh spinner data
To refresh, if you want to keep the existing spinner list as such, and add the new value, then refer dynamic add data to spinner but not update the data on the spinner

Categories

Resources