retrieving hashmap contents?
Hey all, im new here!
How do i retrieve the contents stored within a hashmap?
This is my structure:
recipes(recipeName, ingredients)
recipes being the hashmap, recipeName being a string and ingredients being an array.
How would i retrieve the contents from this hashmap and then output say, the first entry into the relevant textboxes?
I simply can't figure it out. It's driving me mad!
Any help is appreciated!!
[463 byte] By [
Armadilloa] at [2007-11-26 17:40:15]

Maybe I don't understand your question.Call the get() method. Look in the API for details: http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
Object ingredients = null;jTextField2.setText((String) recipes.get(ingredients));well say i have that on a button actionlistener. It doesn't display anything in the textbox and the hashmap is definately populated.
> Object ingredients = null;
> jTextField2.setText((String)
> recipes.get(ingredients));
>
> well say i have that on a button actionlistener. It
> doesn't display anything in the textbox and the
> hashmap is definately populated.
In your original post your key was the recipeName. But in the example you are using the ingredients as the key.
> In your original post your key was the recipeName. But in the example you are using the ingredients as the key.An in any case, isn't ingredients null, since you just assigned null to it on the previous line?
> This is my structure:
> recipes(recipeName, ingredients)
>
> recipes being the hashmap, recipeName being a string
> and ingredients being an array.
>
> How would i retrieve the contents from this hashmap
> and then output say, the first entry into the
> relevant textboxes?
If ingredients is an array of String:
String[]ingredients = (String[])recipes.get(recipeName);
theTextField.setText(ingredients[0]);
If you are using string array in the hashmap, you can get ingredients by casting to string array.String [ ] ingredients = ( String [ ] ) recipes.get(recipeName);
This may sound real stupid, but what would i define recipeName as? I really appreciate your help by the way! :)
I had this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String recipeName = null;
SaveAndLoad recipesLoad = new SaveAndLoad(recipes);
recipesLoad.loadFromFile();
String[]ingredients = (String[])recipes.get(recipeName);
jTextField1.setText(ingredients[0]);
}
and i got this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at submission2.MainForm.jButton1ActionPerformed(MainForm.java:292)
at submission2.MainForm.access$300(MainForm.java:18)
at submission2.MainForm$4.actionPerformed(MainForm.java:220)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
BUILD SUCCESSFUL (total time: 3 seconds)
What's on MainForm.java line 292
Your problem, at least the one that jumps out at me immediately, is that recipeName is null. You never assign it a value. So therefore, recipes.get() returns null, and when you try to access ingredients you get the NPE. ~Tim
This is what's giving me the error:jTextField1.setText(ingredients[0]);
> This may sound real stupid, but what would i define> recipeName as? I really appreciate your help by the> way! :)Probably recipeName would be input by the user in a textfield, or selected by the user from a JList.String recipeName =
>Your problem, at least the one that jumps out at me immediately, is that recipeName is null. You never assign it a value. So therefore, recipes.get() returns null, and when you try to access ingredients you get the NPE.
Makes sense. :)
How exactly would i initialize recipeName to retrieve the contents then? It was easy saving the object structure, but retrieving it is making no sense at all.
I don't know how to tell the program to retrieve the object structure from the file in its integrity.
>Probably recipeName would be input by the user in a textfield, or selected by the user from a JList.>String recipeName = nameField.getText();Ahhh! Thanks for the heads up! :)
>Probably recipeName would be input by the user in a textfield, or selected by the user from a JList.
Manually searching the hasmap by typing the recipeName into a textbox can become tedious, especially when you don't know what recipeNames are available.
How would i list all the recipeName keys in a listbox so i could select one and then list all the ingredients in another listbox?
HashMap<String, String[]> recipes = new HashMap<String, String[]>();
String[] test = {"sugar","milk","flour","chocolate chips","brown sugar"};
String rec = "cookies";
recipes.put(rec,test);
recipes.put("cake",test);
recipes.put("Pizza",test);
Iterator<String> it = recipes.keySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
Just use an iterator to iterate over the keys
~Tim
Ok. That makes sense, but for some reason isnt working in my situation :/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SaveAndLoad recipesLoad = new SaveAndLoad(recipes);
recipesLoad.loadFromFile();
Iterator<String> it = recipes.keySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
//JList1.setListData(it.next());
}
}
I don't get a list in the cmd line and it doesn't output to the jlistbox either. Any ideas what i'm doing wrong?
ARe you sure there are any entries in teh HashMap? do a System.out.println("Recipes available: " + recipes.size());just after your load from file command
Nevermind. I've just found a flaw elsewhere :( if i create the hashmap and save it to file and then click the load button, it works fine.
HOWEVER, when i close the program and load it back up again and click load, nothing happens :( so i'm assuming theres a problem elsewhere. I'm so confused :S
Thanks for your help tim! I'll have to try and figure out this problem.
Iterator<String> it = recipesLoad.GetRecipes().keySet().iterator();
while(it.hasNext())
{
dlm2.addElement(it.next());
}
There was a problem actually loading the contents from the file. I added a lil bit of code and it works like a dream! Thanks alot for your help!! :)
Any idea what's wrong with this code? I'm selecting a recipeName from one jList and displaying all the related ingredients into another jList.
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
String firstSel = (String) jList1.getSelectedValue();
jList2.setListData((String[])recipes.get(firstSel));
}
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.JList$4.getSize(JList.java:1231)
at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1129)
at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1098)
at javax.swing.plaf.basic.BasicListUI.getPreferredSize(BasicListUI.java:353)
at javax.swing.JComponent.getPreferredSize(JComponent.java:1582)
at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
at java.awt.Container.layout(Container.java:1401)
at java.awt.Container.doLayout(Container.java:1390)
at java.awt.Container.validateTree(Container.java:1473)
at java.awt.Container.validate(Container.java:1448)
at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
BUILD SUCCESSFUL (total time: 7 seconds)
You can use the Map's (HashMap's) keySet() method to get the keys you defined in a Set that can be used to populate your JList.
I don't really understand :S I think my problem lies where im loading from the file with the button actionlistener, but i'm not for the jlist actionlistener? It's loaded in the recipeName keys into the jlist model but it didnt load in the ingredients and thus can't find them?
I think that's the problem but i can't figure out how to fix it :/
//This SHOULD load the string[] of ingredients into the 2nd
// jList once the recipeName key has been selected from //the 1st jList.
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
String firstSel = (String) jList1.getSelectedValue();
jList2.setListData((String[])recipes.get(firstSel));
}
//This loads the file when clicked, then populates the first
//jlist with the recipeName keys.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SaveAndLoad recipesLoad = new SaveAndLoad(recipes);
recipesLoad.loadFromFile();
Iterator<String> it = recipesLoad.GetRecipes().keySet().iterator();
while(it.hasNext())
{
dlm2.addElement(it.next());
}
}
private void addToListActionPerformed(java.awt.event.ActionEvent evt) {
fileLoad recipesLoad = new fileLoad(recipes);
recipesLoad.loadFromFile();
int i = recipeList.getSelectedIndex();
requiredIngredients.setListData((String[])recipes.get(dlm.getElementAt(i)));
}
The above should allow me to select a recipeName (hash key) from the left jlist and populate the right jlist with the ingredients. But i'm getting a null pointer exception on the last line. Anyone know how to fix this?
Take this a little slower. First of all are you even sure something is selected when the code is executed? Try adding a print statement that shows you the currently selected "value" in your list. Second, try adding another print statement that prints the value you get from your HashMap when trying to get the ingredients for that selected value.
I added these 2 lines of code:
System.out.println(dlm.getElementAt(i));
System.out.println((String[])recipes.get(dlm.getElementAt(i)));
First line gives me the the key value which was loaded in higher up in the code. Second line gives me:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at assignment2part2.MainForm.addToListActionPerformed(MainForm.java:134)
at assignment2part2.MainForm.access$000(MainForm.java:18)
at assignment2part2.MainForm$1.actionPerformed(MainForm.java:57)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
at java.awt.Component.processMouseEvent(Component.java:5488)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
at java.awt.Component.processEvent(Component.java:5253)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1774)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
:/
> I added these 2 lines of code:
> > System.out.println(dlm.getElementAt(i));
> System.out.println((String[])recipes.get(dlm.getElementAt(i)));
>
> First line gives me the the key value which was
> loaded in higher up in the code. Second line gives
> me:
Then recipes is null or recipes does not contain a value for the key "dlm.getElementAt(i)". Try:
System.out.println(recipes);
System.out.println(recipes.get(dlm.getElementAt(i));
One of those should print "null".
Since an array doesn't define toString, you'll get some weird looking outputs (try it--you'll see what I mean) for the non-null ingredient lists. But, at least you'll see what is null.