Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: get element of ArrayList.

  1. #1
    Junior Member
    Join Date
    Mar 2010
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default get element of ArrayList.

    I have an arraylist as follows and I am trying to get an element so that it can be used in an if statement for evaluation. Is there a way to do this.

    ArrayList<MusicRecording> info = myDataAccessor.getRecordings(category);
     
    //This is what I want to do
    if(info.get(3) == 1){
       //Do Something
    }


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: get element of ArrayList.

    You were correct with your call to info.get(3) to get the element in index 3, but you were wrong to compare it with 1. I assume MusicRecording is not a number. What variable in MusicRecording are you wanting to look at?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Mar 2010
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: get element of ArrayList.

    MusicRecording is a class. I want to look at the value returned by getOwned();

    public class MusicRecording extends Recording {
     
    	/**
    	 *  Data members
    	 */
    	private String artist;
    	private int year;
    	private String gameDescr;
    	private String owned;
    	private String link;
     
     
     
    		public MusicRecording(String theArtist, String theGameDescr,
    						  String theTitle, 
    						  String theCategory, String theImageName, int theYear,String theOwned, String theLink) {
     
    		super(theTitle, theCategory, theImageName);
     
    		artist = theArtist;
    		year = theYear;
    		gameDescr = theGameDescr;
    		owned = theOwned;
    		link = theLink;
     
    	}
     
     
    	public String getArtist() {
    		return artist;
    	}
     
    	public String getDescr(){
    		return gameDescr;
    	}
     
    	public int getYear(){
    		return year;
    	}
     
    	public String getOwned(){
    		return owned;
    	}
     
    	public String getLink(){
    		return link;
     
    	}
     
     
    		public String toString() {
     
    		//display the Name of the Game and other info
    		return getTitle() + "," + "   " + getArtist() + "," + "   " + getYear() + getOwned();
    	}
     
     
     
    		public int compareTo(Object object) {
     
    		MusicRecording recording = (MusicRecording) object;
    		String targetArtist = recording.getArtist();
     
    		return artist.compareTo(targetArtist);
    	}
     
    }

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: get element of ArrayList.

    Ok, getOwned() returns a String, not an int, so you cannot compare it to 1 (and you should compare Strings with the .equals() method, not == ). Looking back up at your origional post, you can get the value the getOwned() method of the MusicRecording object in index 3 by saying:
    String value = info.get(3).getOwned(); //where value is what the getOwned() method returns

    Can you give examples of what values are you expecting your owned variable to be?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    Mar 2010
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: get element of ArrayList.

    Sure. Simply "Yes" or "No". Those are the only two values the "owned" variable can contain. it gets trickey though. See where say myDataAccessor.getRecordings(category);

    That comes from this class.

     
    import java.util.*;
    import java.util.logging.Logger;
    import java.sql.*;
     
     
    public class MusicDataAccessor {
     
    	/**
    	 * Logger for the messages
    	 */
    	private static Logger logger = Logger.getLogger("crs471");
     
    	private Connection myConn;
     
    	private String system;
     
     
     
     
     
    	protected static String owned;
     
    	/**
    	 * Constructs the data accessors.
    	 */
    	public MusicDataAccessor() {
     
    		//  TO DO:  Complete the steps below.
    		//
    		//			For help, see the hints online
     
    		try {
    			// 1. Load database driver
    			//         - driver name = com.mysql.jdbc.Driver		
    			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     
                String database =  "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/users/mfierro/desktop/Project/RainForest.mdb;";
    			// 2. Connect to database
    			//         - DB URL 	= jdbc:mysql://localhost:3306/rainforestdb
    			//		   - user name 	= student
    			//		   - password 	= student
    			myConn = DriverManager.getConnection(
    					database, "", "");
     
    			logger.info("Connection successful");
    		} catch (Exception exc) {
    			logger.severe(exc.toString());
    		}
    	}
     
    	/**
    	 * Returns a sorted list of the categories for the recordings.
    	 */
    	public ArrayList<String> getCategories() {
     
    		//  TO DO:  Complete the steps below.
    		//
    		//			For help, see the hints online
     
    		// 3. Create an empty ArrayList of <String> for the categories
    		ArrayList<String> categories = new ArrayList<String>();
     
    		Statement myStmt = null;
    		ResultSet myRs = null;
     
    		try {
     
    			// 4. Execute query with the given sql
    			String sql = "SELECT name FROM Music_Categories order by id asc";
     
    			myStmt = myConn.createStatement();
    			myRs = myStmt.executeQuery(sql);
     
    			// 5. Process result and place data in the categories ArrayList
    			while (myRs.next()) {
    				final String category = myRs.getString("name");
    				categories.add(category);
    			}
     
    		}
    		catch (SQLException exc) {
    			logger.severe(exc.toString());
    		}
    		finally {
    			// 6. Close the result set and the statement
    			//    - NOTE: DO NOT CLOSE THE CONNECTION, "myConn"
     
    			try {
    				if (myRs != null) {
    					myRs.close();
    				}
     
    				if (myStmt != null) {
    					myStmt.close();
    				}
    			}
    			catch (Exception exc) {
    				logger.severe(exc.toString());
    			}
    		}
     
    		// 7. Return the categories ArrayList
    		return categories;
    	}
     
     
     
     
    	/**
    	 * Returns a sorted list of recordings that match a given category
    	 *
    	 * @param category
    	 *            the category for requested recordings.
    	 * @return collection of <code>MusicRecording</code> objects
    	 */
     
    	public ArrayList<MusicRecording> getRecordings(String category) {
     
    		ArrayList<MusicRecording> recordingList = new ArrayList<MusicRecording>();
     
    		logger.info("Getting a list of recordings for: " + category);
     
     
    		//select the system for the query based on the tab that is currently selected
     
    	    if (MainFrame.sel == 0){
    	    	 system="snes";
    	    }
     
    	    if (MainFrame.sel == 1){
    	    	 system="sega";
    	    }
     
    	    if (MainFrame.sel == 2){
    	    	 system="sega32X";
    	    }
     
    	    if (MainFrame.sel == 3){
    	    	 system="sms";
    	    }
     
    		String sql = "SELECT * FROM Music_Recordings where category='" + category + "' and system='" + system + "'";
     
    		Statement myStmt = null;
    		try {
    			myStmt = myConn.createStatement();
    			ResultSet myRs = myStmt.executeQuery(sql);
     
    			while (myRs.next()) {
    			//	int recordingId = myRs.getInt("recording_id");
    				String artist = myRs.getString("publisher");
    				String title = myRs.getString("title");
    				String imageName = myRs.getString("image_name");
    				String gameDescr = myRs.getString("descr_name");
    				int year = myRs.getInt("release_yr");
    				String owned1 = myRs.getString("num_tracks");
    				String link = myRs.getString("link");
    				//String publisher = myRs.getString("publisher");
     
     
     
     
     
    				MusicRecording tempRecording = new MusicRecording(artist, gameDescr, title, category, imageName,year,owned1,link);
     
     
    				recordingList.add(tempRecording);
     
     
     
    				}
     
    		}
    		catch (SQLException exc) {
    			logger.severe(exc.toString());
    		}
    		finally {
    			close(myStmt);
    		}
     
    		logger.info("getRecordings() complete!\n");
     
    		return recordingList;
    	}
     
     
    	protected void close(Statement theStatement) {
    		try {
    			if (theStatement != null) {
    				theStatement.close();
    			}
    		} catch (SQLException exc) {
    			logger.severe(exc.toString());
    		}
    	}
    }

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: get element of ArrayList.

    If it is only ever yes or no, then you should probably be using a boolean instead. A boolean is a simple-type whose only values can be true or false. Booleans are FAR easier to work with than Strings, since booleans are not objects, they are easier to set, and they are easier to use in logicial conditions (such as if statements). Here is a useful link: Java: Boolean

    booleans can be set several ways. Such as simply saying:
    boolean b = false;
    b = true;
    b = false;
    They can even be set with logical operations. For example, if we had two ints (intA and intB) and we wanted boolean b to be set to true whenever intA is greater than intB, we could say:
    int intA = 4;
    int intB = 2;
    boolean b = intA > intB; //sets b to true in this case, since 4 > 2

    Or you can set them with methods that return true or false values. For example, if we had to Strings (strA and strB) and we wanted boolean b to be set to true whenever strA is the same text as strB, we could say:
    String strA = "Some Text";
    String strB = "Some Text";
    boolean b = strA.equals(strB); //sets b to true in this case, since strA and strB are the same
    Last edited by aussiemcgr; May 11th, 2012 at 03:18 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #7
    Junior Member
    Join Date
    Mar 2010
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: get element of ArrayList.

    I have tried what you suggested and I am still getting errors. Could this be b/c I am trying to do this on an actionlistener event.

    First, here is the constructor for the music recording which contains "owned"
    public MusicRecording(String theArtist, String theGameDescr,
    						  String theTitle, 
    						  String theCategory, String theImageName, int theYear,boolean theOwned, String theLink)

    Here is where I create the array list of music recordings and attempt to get the value of the boolean.

    class GoActionListener implements ActionListener {
    		public void actionPerformed(ActionEvent event) {
     
    			// Get the selected category from the "categoryComboBox"
    			String category = (String) categoryComboBox.getSelectedItem();
    			System.out.println(category);
     
    			// Get the recordings
    			ArrayList<MusicRecording> info = myDataAccessor.getRecordings(category);
    			boolean own = musicRecording.getOwned();
    			System.out.println(own);
    			// Populate the list box
    		  //   if(own == ("Yes")){
    		   //     System.out.println("have the value");
    		   //     musicListBox.setListData(info.toArray());
    		   //     }
    		   //     else{
    		   //     System.out.println("Failed");
    				musicListBox.setListData(info.toArray());
    		   //   }
    			}
     
     
    		}



    ERRORS:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.learningtree.crs471.GamePanelGUI$GoActionListe ner.actionPerformed(GamePanelGUI.java:132)
    at javax.swing.JComboBox.fireActionEvent(Unknown Source)
    at javax.swing.JComboBox.setSelectedItem(Unknown Source)
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
    at javax.swing.plaf.basic.BasicComboPopup$Handler.mou seReleased(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at javax.swing.plaf.basic.BasicComboPopup$1.processMo useEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Last edited by gammaman; May 14th, 2012 at 07:12 AM.

  8. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: get element of ArrayList.

    What line is 132? A null pointer means you have not initialized something.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. How to use an ArrayList and what is its advantage over array?
    By JavaPF in forum Java SE API Tutorials
    Replies: 4
    Last Post: December 21st, 2011, 04:44 AM
  2. Arraylist removing element
    By Stn in forum Loops & Control Statements
    Replies: 6
    Last Post: January 9th, 2011, 08:14 PM
  3. Ordering ArrayList by 3 conditions as you add to ArrayList
    By aussiemcgr in forum Collections and Generics
    Replies: 4
    Last Post: July 13th, 2010, 02:08 PM
  4. new arrayList element overwrites all previous
    By twinkletoes in forum Object Oriented Programming
    Replies: 2
    Last Post: April 2nd, 2010, 07:45 AM
  5. How to use an ArrayList and what is its advantage over array?
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 1
    Last Post: May 17th, 2009, 01:12 PM