Hi i am converting from kilo to stone-pounds, i want to place stones in one edittext and pounds in one edittext , below is my method
public ArrayList<HashMap<String, Integer>> kiloTostomepound(int s) {
int stone = (int) (s * 2.2);
int stonevalue = stone/14;
int spound = (stone % 14);
arrayList = new ArrayList<HashMap<String,Integer>>();
HashMap<String, Integer> h1 = new HashMap<String, Integer>();
h1.put(STONE,stonevalue);
h1.put(STONEPOUND, spound);
arrayList.add(h1);
return arrayList;
}
i want to get values from the arryalist and set it to edittext.
Doing a below but givinf nullpointerexception
edt2.setText(String.valueOf(kiloTostomepound(arrayList.get(0).get(STONE))));
edt3.setText(String.valueOf(kiloTostomepound(arrayList.get(1).get(STONEPOUND))));
The below code traverses through the list and prints key and value.
for (int a =0; a<myList.size();a++)
{
HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(a);
Set<String> key = tmpData.keySet();
Iterator it = key.iterator();
while (it.hasNext()) {
String hmKey = (String)it.next();
Integer hmData = (Integer) tmpData.get(hmKey);
System.out.println("Key: "+hmKey +" & Data: "+hmData);
it.remove(); // avoids a ConcurrentModificationException
}
}
So if you need the first value try following.
HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(0);
Set<String> key = tmpData.keySet();
Iterator it = key.iterator();
// Get the first element
String hmKey = (String)it.next();
Integer hmData = (Integer) tmpData.get(hmKey);
// Set the key and value to Edit text
edt2.setText(hmKey+" "+hmData);
Seems like your assigning the value to the arrayList variable inside of the method. Hence the
kiloTostomepound(arrayList.get(0).get(STONE))
Will throw a nullpointer for arrayList.
If I understand your code correctly, the below code should do the trick. But I don't know the input for the kiloTostomepound method.
edt2.setText(String.valueOf(kiloTostomepound("INPUT TO METHOD").get(0).get(STONE)));
edt3.setText(String.valueOf(kiloTostomepound("INPUT TO METHOD").get(1).get(STONEPOUND)));
This is because your method returns the arrayList with the hashmaps inside.
Related
Please any one can help how to remove particular key from hashmap and then rearrange the keys in hashmap accordingly.
Below is my code.
Set<Integer> integerSet = hashMap.keySet();
int removekey = pos;
ArrayList<Integer> integers = new ArrayList<>();
for (Integer integer : integerSet) {
if (integer > removekey) {
integers.add(integer);
}
}
for (Integer integer : integers) {
if (hashMap.containsKey(integer)) {
AddCardPojo pojo = hashMap.get(integer);
pojo.setImagCard(cardImage[integer - 1]);
hashMap.remove(integer);
hashMap.put(integer - 1, pojo);
}
}[![enter image description here][1]][1]
I have attached screenshot of error
You can directly remove a key value pair,you can directly do
hashMap.remove(removeKey);
as for 're arranging keys in hashmap',
it is a data structure which makes no guarantees of order of data.
Check this answer for more
If you need a particular order as per integer, you could use arraylist
Finally it could be done.
Below is my answer.
hashMap.remove(key);
List<AddCardPojo> hashMapsList=new ArrayList<>();
Iterator it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
hashMapsList.add((AddCardPojo) pair.getValue());
}
hashMap = new HashMap<>();
for(int i=0; i<hashMapsList.size();i++){
hashMap.put(i,hashMapsList.get(i));
}
I am trying to implement Searching in ListView. My ListView is comprised of HashMap in ArrayList and I managed to implement the logic but I guess there is much object and memory allocation in my approach each time the text change. Therefore I am looking for less memory allocated logic to search in my ListView with HashMap in ArrayList
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//textlength = searchBar.getText().length();
//text_sort.clear();
sortedArrayList.clear();
for (int i = 0; i < myHistList.size(); i++) {
HashMap<String, String> hash = new HashMap<String, String>();
hash = myHistList.get(i);
if (hash.get("myName").toLowerCase().indexOf(searchBar.getText().toString().toLowerCase()) != -1) {
String callerNum1 = hash.get("myNumber");
String myName1 = hash.get("myName");
HashMap<String, String> searchedHash = new HashMap<String, String>();
// adding each child node to HashMap key => value
searchedHash.put("myNumber", callerNum1);
searchedHash.put("myName", myName1);
recordingFile1);
// adding HashList to ArrayList
sortedArrayList.add(searchedHash);
}
}
ListView actualLv = mPullRefreshListView.getRefreshableView();
actualLv.setAdapter(new myHistoryListAdapter(myHistory.this, sortedArrayList));
}
At first you can replace
HashMap<String, String> hash = new HashMap<String, String>();
hash = myHistList.get(i);
with just
HashMap<String, String> hash = myHistList.get(i);
It will slightly reduce the number of redundant objects.
At second step if you need to compare strings are the same but ignore letters' case you can try to simplify your if condition
if (hash.get("myName").toLowerCase().indexOf(searchBar.getText().toString().toLowerCase()) != -1)
with
if(hash.get("myName").compareToIgnoreCase(searchBar.getText().toString()) == 0)
Also if you put the String callerNum1 = hash.get("myNumber"); above the if statement then you can save some time because you don't need to look through your HashSet two times to search the same element. It will look like following:
String callerNum1 = hash.get("myNumber");
if(callerNum1.compareToIgnoreCase(searchBar.getText().toString()) == 0){
...
}
private HashMap<String, String> mHashMap = new HashMap<String, String>();
mHashMap.put("a", "ajay");
mHashMap.put("h", "hiren");
mHashMap.put("d", "darshan");
mHashMap.put("a", "anand");
mHashMap.put("h", "harsah");
for (String key: mHashMap.keySet()) {
Log.e(key,"" + mHashMap.get(key));
}
My Result:
d - darsha
h - harshad
a - anand
I want all values from HashMap?
If you have any idea related to it, then help me.
HashMap will override the value if a key for that value exists already. If you need to have more values for a key, you should use a Collection as value fro your HashMap:
private HashMap<String, Vector<String>> mHashMap = new HashMap<String, Vector<String>>();
Vector<String> tmp = new Vector<String>();
tmp.add("ajay");
tmp.add("anand");
mHashMap.put("a", tmp);
tmp = new Vector<String>();
tmp.add("hiren");
mHashMap.put("h", tmp);
and so on..
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.
I have worked in soap message, and to parse the value from Webservice, the values are stored in ArrayList.
Example:
values are Employee name (Siva) and Employee id (3433fd), these two values are stored in arraylist, but I want to stored in Dictionary, How?
you can use HashMap like this
Map <String,String> map = new HashMap<String,String>();
//add items
map.put("3433fd","Siva");
//get items
String employeeName =(String) map.get("3433fd");
You can use Bundle.
as it offers String to various types of Mapping.
Bundle b = new Bundle();
b.putInt("identifier", 121);
b.putString("identifier", "Any String");
b.putStringArray("identifier", stringArray);
int i = b.getInt("identifier");
...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText textview = (EditText) findViewById(R.id.editTextHash);
EditText textviewNew = (EditText) findViewById(R.id.editTextHash2);
Map<String, String> map = new HashMap<String,String>();
map.put("iOS", "100");
map.put("Android", "101");
map.put("Java", "102");
map.put(".Net", "103");
String TextString = "";
// Set<E> keys = map.keySet();
Set keys = map.keySet();
System.out.println("keys "+keys);
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
System.out.println("key "+key);
String value = (String) map.get(key);
System.out.println("value "+value);
textview.append(key + " = " + value);
TextString+=(key + " = " + value);
}
//textviewNew.setText(TextString);
// Iterator iterator = map.keySet().iterator();
//
// while (iterator.hasNext())
// {
// String object = (String) iterator.next();
// textview.setText(object);
// }
//
// //textview.setText(map.get("Siva"));
//
// System.out.println(map);
}
}
A Dictionary is an abstract class that maps keys to values and there is Dictionary Class in android refer link you can find a note at Class Overview
Do not use this class since it is obsolete. Please use the Map
interface for new implementations.
An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException,but you can use Map interface,it provides the exact same functionality of a dictionary.you can use it as bellow
//put values
Map Message = new HashMap();
Message.put("title", "Test message");
Message.put("description", "message description");
Message.put("email", "email#gmail.com");
//get values
Log.d("get Message","Message title -"+Message.get("title"));
you can also use A custom class as below
public class MessageObject {
String title;
String description;
String email;
}
you can use Getters and Setters to get and put values,not needed to remember the key names every time you may get some other advantages by this way.