Passing an array of objects to a method.

Hi I'm building a program to act as a CD Collection Database. An array of objects represents the entries: Artist, Album and NUmber of Tracks. What I want to do is in the Menu, user to choose wether he or she wants to Add new CD to collection, print or quit, if he/she does then I call a method addNewEntry, to which i pass the array of objects called array, and I want the user to enter the entries each in turn, after that i want the program to return to the method Menu and ask if he or she wants to quit, print or add new cd. The idea is that the details entered already would be contained in the array of objects [0], so the next set of details go to [1] and then to [2] and so on. I have build up the code at this stage but i get an error while copmiling and im totally stuck. Im a beginner in Java.
Here is the code:
//by Andrei Souchinski
//Mini Project: CD Collection Database
//Designed for a grade F
//Defining new class of objects to represent CD database entries.
//A database entry consists of the artist name, the album name and number of tracks.
//A single entry can be entered by the user typing the details in and the entry can be printed out.
import javax.swing.*;
import java.util.*;
public class MiniProject
     public static void main (String[] args)     
          System.out.println("\tCD Collection Database\n");
          System.out.println("1. Add new Compact Disk to the Database");
          System.out.println("2. Print out current database entries");
          System.out.println("3. Quit\n");          
          theMenu();
     public static void theMenu()
          CompactDisk [] array = new CompactDisk[20];
          String menu;
          menu = JOptionPane.showInputDialog("What would you like to do?");
          if (menu.equals ("3"))
               JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
               System.exit(0);     
          if (menu.equals ("2"))
          if (menu.equals ("1"))
          addNewEntry(array);
          else
               JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
               theMenu();
     public int addNewEntry(int newcd[])
               int i;          
               newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
               newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Album"));
               newcd[i] = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
//A Compact Disk entry consists of three attributes: artist name, album and number of tracks
class CompactDisk
     public String artistname; //Instance variables for artistname, albumname and numberoftracks.
     public String albumname;
     public int numberoftracks;
     public CompactDisk(String n, String a, int t)
     artistname = n; //Stores the 1st argument passed after "new Dates" into day
     albumname = a; //Stores the 2nd argument passed after "new Dates" into month
     numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
     //When called from the main method, prints the contents of
     //artistname, albumname and numberoftracks on to the screen.
     public void printCompactDisk ()
               String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
               System.out.println(output);
}

//by Andrei Souchinski
//Mini Project: CD Collection Database
//Designed for a grade F
//Defining new class of objects to represent CD database entries.
//A database entry consists of the artist name, the album name and number of tracks.
//A single entry can be entered by the user typing the details in and the entry can be printed out.
import javax.swing.*;
import java.util.*;
public class MiniProject
     public static void main (String[] args)     
          System.out.println("\tCD Collection Database\n");
          System.out.println("1. Add new Compact Disk to the Database");
          System.out.println("2. Print out current database entries");
          System.out.println("3. Quit\n");          
            theMenu();
     public static void theMenu()
          String menu;
          menu = JOptionPane.showInputDialog("What would you like to do?");
          if (menu.equals ("3"))
               JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
               System.exit(0);     
          if (menu.equals ("2"))
          if (menu.equals ("1"))
          addNewEntry();
          else
               JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
               theMenu();
     public static void addNewEntry()
               CompactDisk [] array = new CompactDisk[20];
               int i = 0;
               array.artistname = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
               array[i].albumname = (JOptionPane.showInputDialog("Please enter the name of the Album"));
               array[i].numberoftracks = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
//A Compact Disk entry consists of three attributes: artist name, album and number of tracks
class CompactDisk
     public String artistname; //Instance variables for artistname, albumname and numberoftracks.
     public String albumname;
     public int numberoftracks;
     public CompactDisk(String n, String a, int t)
     artistname = n; //Stores the 1st argument passed after "new Dates" into day
     albumname = a; //Stores the 2nd argument passed after "new Dates" into month
     numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
     //When called from the main method, prints the contents of
     //artistname, albumname and numberoftracks on to the screen.
     public void printCompactDisk ()
               String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
               System.out.println(output);
I've edited the code, itcompiles, but gives an error when i ran it..:(

Similar Messages

  • Need Help! Passing an array of objects to a method, dont understand

    Hi, i need to make a method called public Server[] getServers() and i need to be able to see if specific server is available for use.
    I have this so far:
    public abstract class AbstractServer
    protected String serverName;
    protected String serverLocation;
    public AbstractServer(String name,String location)
    this.serverName=name;
    this.serverLocation=location;
    public abstract class Server extends AbstractServer
    public Server(String name,String location)
    super(name,location);
    public class CreateServers
    Server server[];
    public CreateServers()
    public Server create()
    for(int i=0; i<10; i++)
    server=new Server(" ", " "); //i was going to fill in something here
    return server;
    OK NOW HERE IS THE PROBLEM
    i have another class that is supposed to manage all these servers, and i dont understand how to do the public Server[] getServers(), this is what i have tried so far
    public class ServerManager()
    public Server[] getServers(Server[] AbstractServer)
    Server server=null; //ok im also confused about what to do here
    return server;
    in the end i need this because i have a thread class that runs the servers that has a call this like:
    ServerManager.getServers("serverName", null);
    Im just really confused because i need to get a specific server by name but i have to go through AbstractServer class to get it
    Any help?

    thanks for replying...
    ok ill remove the Server.java one to be
    public class Server extends AbstractServer
         public Resource(String name,String locaton)
              super(name,location);
    ok so inside ServerManager.java i should have something like
    ArrayList servers;
    public ServerManager()
    servers=new ArrayList();
    ok but i still dont get how to use that in a method
    say if i put it like this
    public getServers()
    //populate server list in here??????
    ok im still lost...

  • Passing an array of objects.

    I have been trying to pass an array of objects from java to C. They are simple objects, only fields, no methods.
    Example...
    class User
    String name;
    int id;
    public class JNIExample
    User[] users = new User[10];
    public native void nativeCode(User[] usersarray);
    static
    try{
    System.loadLibrary("object");
    }catch(Exception e)
    System.out.println("Could not load library.");
    public static void main(String[] args)
    JNIExample anex = new JNIExample();
    anex.nativeCode(anex.users);
    Could someone give me sample code on how to access the array elements and get/set the object values on the C side. In the above code I did not create any of the objects in the array or set their field values but these will be set on the java side.
    Any help would be greatly appr.
    Thanks,
    Darrin

    JNIEXPORT void JNICALL Java_User_nativeCode
      (JNIEnv *env, jobject this, jobjectArray arr) {
      jsize  idx; // array index
      // accessing the Users
      for(idx = env->GetArrayLength(env, arr); idx-- > 0;) {
        jobject user = env->GetObjectArrayElement(env, arr, idx);
        // do something with it
      // setting the Users
      for(idx = env->GetArrayLength(env, arr); idx-- > 0;) {
        jobject user = ...
        env->SetObjectArrayElement(env, arr, idx, user);
    }

  • Passing an array of objects to stored procedure(oracle)

    I have to pass an array of objects to a pl/sql stored proc.
    Its prototype is,
    proc_orderins(ordernum varchar2(14), ct newTask)
    where newTask is an array of objects:
    type task as object ( name varchar2(20),odd varchar2(8),sdd varchar2(8));
    create or replace type newTask as VARRAY(25) OF Task;
    will the following work from the java code :
    public class CriticalTask
    String name,odd,sdd;
    public CrticalTask(String name,String odd,String sdd)
    this.name=name;
    this.odd=odd;
    this.sdd=sdd;
    Object [] ctasks =new Object[7];
    for(i=0;i<7;i++)
    Object=new CrtitcalTask("x","x","x");
    String query="{call proc_orderins(?,?)}";
    CallableStatement cstmt=con.prepareCall(query);
    cstmt.setInt(123);
    cstmt.setObject(ctasks);
    cstmt.execute();
    will the above code work, when I am passing an array?

    Use code tags when you post code.
    I am rather certain that the code you posted will not work.
    Technically you should be able to use the java.sql.Array interface.
    The newest Oracle drivers might support that (you would have to investigate how to use it.)
    It is however possible that it isn't supported. If not then you will have to use one of the Oracle specific classes that is documented in the Oracle jdbc documentation.

  • Passing an array of objects to a named query

    I'm trying to use a named query that will have a
    in() expression operator (clause) to retrieve a set of objects.
    The in() operator requires an array of objects to pass in.
    Specifically I want to pass an array of BigDecimal of unknown size.
    The query looks like that:
    ExpressionBuilder seq = new ExpressionBuilder();
    Expression exp = seq.get("id").in(keys);
    ReadAllQuery query = new ReadAllQuery();
    query.setReferenceClass(RegistrationNumberSequencer.class);
    query.addArgument("keys");
    query.setSelectionCriteria(exp);
    And the "keys" would be:
    Object[] keys = new Object[2];
    keys[0]= new BigDecimal(1);
    keys[1]= new BigDecimal(2);
    I have got a conversion exception(Could not convert to BigDecimal class) when executing the query.
    Can I pass this array as a parameter somehow ?
    Thanks a lot
    Ovidiu

    Hi Ovidiu,
    My apologies for the missed code. You need to pass the vector of elements into another vector, so TopLink will interpret the single element of the second vector as the correct query argument, and expend the elements in the first vector into the IN clause.
    The named query defined I sent in previous mail is still correct, but you need to pass in the argument like:
    Vector keys = new Vector();
    keys.addElement(new BigDecimal(1));
    keys.addElement(new BigDecimal(2));
    Vector arg = new Vector(1);
    arg.addElement(keys);
    Now you can pass the arg in when executing the query, and should get the correct result.
    To stand my claim, I did a mini test using our TopLink Employee demo and here is the generated SQL:
    Call:SELECT t0.VERSION, t1.EMP_ID, t0.L_NAME, t0.F_NAME, t1.SALARY, t0.EMP_ID, t0.GENDER, t0.END_DATE, t0.START_DATE, t0.MANAGER_ID, t0.START_TIME, t0.END_TIME, t0.ADDR_ID FROM EMPLOYEE t0, SALARY t1 WHERE ((t0.EMP_ID IN (1, 2)) AND (t1.EMP_ID = t0.EMP_ID))
    You can see the IN clause in generated as expected!
    As Doug said, we do not officially support array as query argument yet. I would use the proper way to build the query.
    King

  • Passing an array of integers to a method...

    here's the case, i have 2 array of integers parent and child. how can i pass the arrays in a method so i can evaluate the contents of both arrays?
    here's the block of the code that contains what i'm talking about.
    for(int i=0; i<tree.length; i++) {//separate child from parent      
         int[] parent = new int[(tree.length()/2)];
         int[] child = new int[(tree[i].length()/2)];
         for(int j=0, ctr=0; j<tree[i].length(); j++, ctr++) {               
              parent[ctr] = Integer.parseInt(Character.toString(tree[i].charAt(j))); //get the parents
              j++;
              child[ctr] = Integer.parseInt(Character.toString(tree[i].charAt(j))); //get the children
         if(isTree(parent, child)) //evaluate if case is a tree
         System.out.println("Is a tree");
         else
         System.out.println("Is not a tree");
    }//separate child fronm parent     

    geez, thanks... adding "static" did work.. >_< my bad, i'm new in java... and i'm sorry for calling you
    "sir", thanks a lot monica... ^^ by the way, it's 1:00 pm here asia.I'm glad it worked--do you understand what "static" means here?
    No problem about the "sir". I usually use "he" myself, if I don't know whether it should be he/she. And, around here on the forum (and software engineers at most companies), there are certainly more men than women. People tend to look at MLRon and assume my name is "Ron", but that's my last name. :)
    You don't need to call people "sir" or "ma'am" here. Just names or screen names (like MLRon) will do. :)
    Have a nice afternoon, then!

  • Problem passing multiple array lists to a single method

    Hi, all:
    I have written a generic averaging method that takes an array list full of doubles, adds them all up, divides by the size of the array list, and spits out a double variable. I want to pass it several array lists from another method, and I can't quite figure out how to do it. Here's the averager method:
         public double averagerMethod (ArrayList <Double> arrayList) {
              ArrayList <Double> x = new ArrayList <Double> (arrayList); //the array list of integers being fed into this method.
              double total = 0;//the total of the integers in that array list.
              for (int i = 0; i < x.size(); i++) {//for every element in the array list,
                   double addition = x.get(i);//get each element,
                   total = total + addition; //add it to the total,
              double arrayListSize = x.size();//get the total number of elements in that array list,
              double average = total/arrayListSize;//divide the sum of the elements by the number of elements,
              return average;//return the average.
         }And here's the method that sends several array lists to that method:
         public boolean sameParameterSweep (ArrayList <Double> arrayList) {
              sameParameterSweep = false;//automatically sets the boolean to false.
              arrayList = new ArrayList <Double> (checker);//instantiate an array list that's the same as checker.
              double same = arrayList.get(2); //gets the third value from the array list and casts it to double.
              if (same == before) {//if the third value is the same as the previous row's third value,
                   processARowIntoArrayLists(checker);//send this row to the parseAParameterSweep method.
                   sameParameterSweep = true;//set the parameter sweep to true.
              if (same != before) {//if the third value is NOT the same,
                   averagerMethod(totalTicks);//go average the values in the array lists that have been stored.
                   averagerMethod(totalNumGreens);
                   averagerMethod(totalNumMagentas);
                   sameParameterSweep = false;
              before = same; //problematic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         return sameParameterSweep;
         }Obviously, the problem is that I'm not passing the array lists from this method to the averager method the right way. What am I doing wrong?

    Encephalopathic wrote:
    There are several issues that I see, but the main one is that you are calculating average results but then just discarding them. You never assign the result to a variable.
    In other words you're doing this:
    averagerMethod(myArrayList);  // this discards the resultinstead of this:
    someDoubleVariable = averagerMethod(myArrayList); // this stores the resultAlso, do you wish to check for zero-sized array lists before calculating? And what would you return if the array list size were zero?So in solving that problem, I've come up with another one that I can't figure out, and I can't fix this problem until I fix that.
    I have several thousand lines of data. They consist of parameter sweeps of given variables. What I'm trying to do is to store pieces of
    data in array lists until the next parameter adjustment happens. When that parameter adjustment happens, I want to take the arraylists
    I've been storing data in, do my averaging thing, and clear the arraylists for the next set of runs under a given parameter set.
    Here's the issue: I'm having the devil of a time telling my application that a given parameter run is over. Imagine me doing stuff to several variables (number of solders, number of greens, number of magentas) and getting columns of output. My data will hold constant the number of soldiers, and for, say, ten runs at 100 soldiers, I'll get varying numbers of greens and magentas at the end of each of those ten runs. When I switch to 150 soldiers to generate data for ten more runs, and so forth, I need to average the number of greens and magentas at the end of the previous set of ten runs. My problem is that I can't figure out how to tell my app that a given parameter run is over.
    I have it set up so that I take my data file of, say, ten thousand lines, and read each line into a scanner to do stuff with. I need to check a given line's third value, and compare it to the previous line's third value (that's the number of soldiers). If this line has a third value that is the same as the previous line's third value, send this line to the other methods that break it up and store it. If this line has a third value that is NOT the same as the previous line's third value, go calculate the averages, clear those array lists, and begin a new chunk of data by sending this line to the other methods that break it up and store it.
    This is not as trivial a problem as it would seem at first: I can't figure out how to check the previous line's third value. I've written a lot of torturous code, but I just deleted it because I kept getting myself in deeper and deeper with added methods. How can I check the previous value of an array list that's NOT the one I'm fiddling with right now? Here's the method I use to create the array lists of lines of doubles:
         public void parseMyFileLineByLine() {
              totalNumGreens = new ArrayList <Double>();//the total number of greens for a given parameter sweep
              totalNumMagentas = new ArrayList <Double>();//the total number of magentas for a given parameter sweep.
              totalTicks = new ArrayList <Double>();//the total number of ticks it took to settle for a given parameter sweep.
              for (int i = 8; i < rowStorer.size() - 2; i++) {//for each line,
                   checker = new ArrayList <Double>();//instantiates an array list to store each piece in that row.
                   String nextLine = rowStorer.get(i); //instantiate a string that contains all the information in that line.
                   try {
                        Scanner rowScanner = new Scanner (nextLine); //instantiates a scanner for the row under analysis.
                        rowScanner.useDelimiter(",\\s*");//that scanner can use whitespace or commas as the delimiter between information.
                        while (rowScanner.hasNext()) {//while there's still information in that scanner,
                             String piece = rowScanner.next(); //gets each piece of information from the row scanner.
                             double x = Double.valueOf(piece);//casts that stringed piece to a double.
                             checker.add(x);//adds those doubles to the array list checker.
                   catch (NoSuchElementException nsee) {
                        nsee.printStackTrace();
                   //System.out.println("checker contains: " + checker);
                   processARowIntoArrayLists(checker);//sends checker to the method that splits it up into its columns.
         }

  • How to pass a array of object to oracle procedure using callable

    Hi,
    I am calling a oracle stored procedure using callable statement which has IN and OUT parameter of same type.
    IN and OUT are array of objects. (ie) IN parameter as Array of Objects and OUT parameter as Array of Objects
    here are the steps i have done as advised from oracle forum. correct me if i am in wrong direction
    ORACLE types and Stored Procedure
    CREATE OR REPLACE
    TYPE APPS.DEPARTMENT_TYPE AS OBJECT (
    DNO NUMBER (10),
    NAME VARCHAR2 (50),
    LOCATION VARCHAR2 (50)
    CREATE OR REPLACE
    TYPE APPS.DEPT_ARRAY AS TABLE OF department_type;
    CREATE OR REPLACE package body APPS.insert_object
    IS
    PROCEDURE insert_object_prc (d IN dept_array, d2 OUT dept_array)
    IS
    BEGIN
    d2 := dept_array ();
    FOR j IN 1 .. d.COUNT
    LOOP
    d2.EXTEND;
    d2 (j) := department_type (d (j).dno, d (j).name, d(j).location);
    END LOOP;
    END insert_object_prc;
    END insert_object;
    JAVA CODE
    Value Object
    package com.custom.vo;
    public class Dep {
    public int empNo;
    public String depName;
    public String location;
    public int getEmpNo() {
    return empNo;
    public void setEmpNo(int empNo) {
    this.empNo = empNo;
    public String getDepName() {
    return depName;
    public void setDepName(String depName) {
    this.depName = depName;
    public String getLocation() {
    return location;
    public void setLocation(String location) {
    this.location = location;
    to call stored procedure
    package com.custom.callable;
    import com.custom.vo.Dep;
    import oracle.jdbc.OracleCallableStatement;
    import oracle.jdbc.OracleConnection;
    import oracle.jdbc.OracleTypes;
    import oracle.jdbc.pool.OracleDataSource;
    import oracle.sql.ARRAY;
    import oracle.sql.ArrayDescriptor;
    import oracle.sql.Datum;
    import oracle.sql.STRUCT;
    import oracle.sql.StructDescriptor;
    public class CallableArrayTryOut {
    private static OracleDataSource odcDataSource = null;
    public static void main(String[] args) {
    OracleCallableStatement callStatement = null;
    OracleConnection connection = null;
    try {
    odcDataSource = new OracleDataSource();
    odcDataSource
    .setURL("......");
    odcDataSource.setUser("....");
    odcDataSource.setPassword("....");
    connection = (OracleConnection) odcDataSource.getConnection();
    } catch (Exception e) {
    System.out.println("DB connection Exception");
    e.printStackTrace();
    Dep[] dep = new Dep[2];
    dep[0] = new Dep();
    dep[0].setEmpNo(100);
    dep[0].setDepName("aaa");
    dep[0].setLocation("xxx");
    dep[1] = new Dep();
    dep[1].setEmpNo(200);
    dep[1].setDepName("bbb");
    dep[1].setLocation("yyy");
    try {
    StructDescriptor structDescriptor = new StructDescriptor(
    "APPS.DEPARTMENT_TYPE", connection);
    STRUCT priceStruct = new STRUCT(structDescriptor, connection, dep);
    STRUCT[] priceArray = { priceStruct };
    ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(
    "APPS.DEPT_ARRAY", connection);
    ARRAY array = new ARRAY(arrayDescriptor, connection, priceArray);
    callStatement = (OracleCallableStatement) connection
    .prepareCall("{call insert_object.insert_object_prc(?,?)}");
    ((OracleCallableStatement) callStatement).setArray(1, array);
    callStatement.registerOutParameter(2, OracleTypes.ARRAY,
    "APPS.DEPT_ARRAY");
    callStatement.execute();
    ARRAY outArray = callStatement.getARRAY(2);
    Datum[] datum = outArray.getOracleArray();
    for (int i = 0; i < datum.length; i++) {
    oracle.sql.STRUCT os = (oracle.sql.STRUCT) datum[0];
    Object[] a = os.getAttributes();
    for (int j = 0; j < a.length; j++) {
    System.out.print("Java Data Type :"
    + a[j].getClass().getName() + "Value :" + a[j]
    + "\n");
    connection.commit();
    callStatement.close();
    } catch (Exception e) {
    System.out.println("Mapping Error");
    e.printStackTrace();
    THE ERROR
    Mapping Errorjava.sql.SQLException: Inconsistent java and sql object types
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    at oracle.jdbc.dbaccess.DBError.check_error(DBError.java:1130)
    at oracle.sql.StructDescriptor.toOracleArray(StructDescriptor.java:823)
    at oracle.sql.StructDescriptor.toArray(StructDescriptor.java:1735)
    at oracle.sql.STRUCT.<init>(STRUCT.java:136)
    at com.custom.callable.CallableArrayTryOut.main(CallableArrayTryOut.java:48)

    You posted this question in the wrong forum section. There is one dedicated to Java that was more appropriate.
    Anyway here is a link that describes what you should do.
    http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/oraarr.htm#i1049179
    Bye Alessandro

  • Passing an Array Remote Object

    Hi,
    I am a newbie and I've been able to call Java methods when
    they return a simple String. However, I am unable to get a
    collection of Java objects. I get the following error message :
    Type Coercion failed: cannot convert
    mx.rpc.remoting.mxml::Operation@31717b1 to Array.
    I have a datagrid in my application that has to be populated
    by calling a method of a remote object.
    The remote object (Java class looks like this).
    public class PlayerService {
    public PlayerService() {
    public Player[] getPlayersAsArray() {
    Player[] players = new Player[3];
    Player rahul = new Player("Rahul",,"Dravid");
    Player sachin = new Player("Sachin","Tendulkar");
    Player saurav = new Player("Saurav","Ganguly");
    players[0] = rahul;
    players[1] = sachin;
    players[2] = saurav;
    return players;
    I've configured the destination in my service-config.xml as
    <destination id="PlayerService">
    <properties>
    <source>rpc.playerinfo.PlayerService</source>
    <scope>application</scope>
    </properties>
    </destination>
    My mxml application code is given below :
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.collections.ArrayCollection;
    import rpc.playerinfo.Player;
    import mx.utils.ArrayUtil;
    [Bindable]
    public var players:ArrayCollection;
    public var myPlayer:Player;
    ]]>
    </mx:Script>
    <mx:RemoteObject
    id="playMe"
    destination="PlayerService"
    showBusyCursor="true">
    <mx:method name="getPlayersAsArray">
    <mx:arguments>
    </mx:arguments>
    </mx:method>
    </mx:RemoteObject>
    <mx:ArrayCollection id="playerList"
    source="{playMe.getPlayersAsArray}"/>
    <mx:DataGrid dataProvider="playerList" width="100%">
    <mx:columns>
    <mx:DataGridColumn dataField="FirstName"
    headerText="FirstName"/>
    <mx:DataGridColumn dataField="LastName"
    headerText="LastName"/>
    </mx:columns>
    </mx:DataGrid>
    </mx:Application>
    One question I have is, how does Flex know that what's
    returned is an array of Player objects. I did define the Player in
    an Action script file.
    package rpc.playerinfo
    [RemoteClass(alias="rpc.playerinfo.Player")]
    [Bindable]
    public class Player
    public var firstName:String;
    public var lastName:String;
    public function Player() {}
    but it appears that I have never actually used it in the mxml
    file.
    Thank you very much.

    Thanks guys.
    JS, I got what you are saying. Now I don't have any error
    messages, but the data grid is blank.
    This is the mxml code. (I added your input)
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.collections.ArrayCollection;
    import rpc.playerinfo.Player;
    import mx.utils.ArrayUtil;
    [Bindable]
    public var players:ArrayCollection;
    public function handlePlayersResult(event: ArrayCollection)
    //then set the event result which is being sent into this
    function to the playerList
    players = event;
    ]]>
    </mx:Script>
    <mx:RemoteObject id="playMe" destination="PlayerService"
    showBusyCursor="true">
    <mx:method name="getPlayersAsArray"
    result="handlePlayersResult(event.result as ArrayCollection)"/>
    </mx:RemoteObject>
    <mx:DataGrid dataProvider="{players}" width="100%"
    creationComplete="playMe.getPlayersAsArray()">
    <mx:columns>
    <mx:DataGridColumn dataField="firstName"
    headerText="FirstName"/>
    <mx:DataGridColumn dataField="lastName"
    headerText="LastName"/>
    </mx:columns>
    </mx:DataGrid>
    </mx:Application>
    What is it missing ?
    Thank you so much.

  • How to pass array of Object in A Procedure using OCCI.......

    I m also trying for How to pass Object to a procedureb using OCCI...
    Steps....
    1. I created A type.....
    2. Then I created a VARRAY using that Type.
    3.After that I have written An Procedure with object as a parameter..
    now using OCCI how do u bind the parameter with this . plz note that using OTT
    i have already created the class representation of above object type i.e class
    four Files Created 1> demo.h 2>registermapping.h
    3> demo.cpp 2>registermapping.cpp
    After I want to Pass the Values in A Vector...
    vctor<full_name *> vect;
    stmt=con->createStatement("BEGIN Add_Object(:1); END;");
    full_name *name1 = new full_name; //Giving the Error here Given below....
    name1->
    name1->
    Through name1 Which Function I will call in which I will Pass a String....
    like
    name1->readSQL("Sanjay"); Or I have to add a function......
    vect.push_back(name1);
    setVector(stmt,1,vect,"FULL_NAME");
    error C2259: 'FullName' : cannot instantiate abstract class
    can u plz suggest me Why this Error is Giving......?
    How to pass the data?
    setFirst_name() and setLast_name() this two function I will add in Demo.cpp which one created automativcally by Using OTT command.....or other way plz tell me Boss ....
    Can u lz Suggest me ASAP....

    hi Nishant ,
    What u have done Now I mm trying ....
    can u Plz Suggest me......
    How to pass and Array of Object in Procedure using OCCI... Doing....
    90% finished Two Error's Are Coming...
    1> If I create the Class then Data Not Inserting table......
    2> If I will create the Class through OTT command.......
    then U can't Instantiate Object It is DIsplying ,this is Abstract Class(PObject)...
    Beco'z the below Method is Not adding Automatically by OTT command which is Pure Virtual Function.....
    But I added this Function Still SAme Error Giving..
    getSQLTypeName(oracle::occi::Environment env, void *schName,
    unsigned int &schNameLen, void **typeName,
         unsigned int &typeNameLen) const
    Plz Suggest me....
    regard's
    sanjay

  • Creating an array of objects of a class known ONLY at RUNTIME

    I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
    Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
    Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
    Thanks a lot in advance.

    Sorry, for the small typo. It is -
    clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
    instead
    Thanks for the reply. I could do this. But I am
    getting a handle to the method to be 'invoke'd by
    looking at the types of the parameters its
    expecting(getParameterTypes). So I can't change it to
    accept an array of Generic Objects.
    I looked at the java.lang.reflect.Array class to do
    this. This is what I am trying to do-
    String variableName is an input coming into my
    program.
    n is the size of the array I'm trying to create.
    Class clazz = Class.forName(variableName);
    clazz[] arr = (clazz
    [])java.lang.reflect.newInstance(clazz, n);
    According to Reflection API, it should work, right?
    But compiler yells at me saying 'class clazz not
    found'.
    Any suggestions/hints/help?
    Thanks, again.

  • Pass an ArrayList of objects from C++ to JAVA using JNI

    Hello,
    I need to get the running Windows processes using C++ and have a Process struct in C++ having 2 fields: name and pid. I want to pass an ArrayList of Process from C++ to Java. I have found an example of how to pass an array of objects from C++ to Java, but I'd like to pass an ArrayList, and I was wondering if this is possible, before understanding that example and use an array.
    I don't have much experience with C++ and I don't even know if you have something like an ArrayList in C++, so I'm sorry if it doesn't make any sense what I'm talking about. Thank you.

    From C you can access and/or imnstantiate one of the
    java collections. In other words, your C code should
    simply populate java structures and a collection.I have read this is possible after I posted this, but didn't find an example yet. I began reading "Java Native Interface" book from Addison-Wesley today to get a better understanding of JNI.
    If you know where to find an example of doing this, I would appreciate it. Otherwise, I suppose I will find this in the above mentioned book quite soon... Thank you.

  • Creating array of object

    Using JNI, I'm trying to pass an array of object from the C native side to
    the Java side. I have the following code:
    JNIEXPORT jint JNICALL Java_classA_methodB(
    JNIenv *env,
    jobject obj,
    jobjectArray objArr )
    jclass objClass = ( *env )->FindClass( env, "arrObjClass" );
    jmethodID methodID = ( *env )->GetMethodID( env, objClass, "<init>", "()V" ); // Default constructor
    jobject objElement = ( *env )->NewObject( env, objClass, methodID );
    // ... Fill objElement with values
    ( *env )->SetObjectArrayElement( env, objArr, 0, objElement ); // <-- program core dumps here.  WHY? 
    return 1;
    The program core dumps at the line above and I don't understand why?
    objArr is originally set to null when pass to the native function. Does
    objArr have to be allocated using new before pass to the native function?
    Thank you in advance,
    Duong

    You seem to be trying to write into an array passed as an input argumenet, when you haven't in fact passed an array object.
    (At least that's what I interpreted you to say what you are doing.)
    Either construct an array in java and pass it to C++, or if that is probelmatic, then change the C++ return object from an int to an array, and do the construction in C++.

  • Pass an array of images???

    I am very new to java and my instructor gave us an assignment of doing a matching game using JButtons and an applet. I have 2 separate .java files (MemoryApplet.java and MemoryGame.java). MemoryApplet intializes the applet and passes an array of images to a method using the following code...
    icon = new MemoryGame();
    for(int i = 0;i<6;i++)
    imgArr[i] = getImage(getCodeBase(),"img" i".jpg");
    icon.setTheIcons(imgArr);
    In the MemoryGame file my setTheIcons method looks like this...
    public void setTheIcons(Image icon1[])
    The problem I am having is that I cannot convert the Image to an ImageIcon to put the image on the JButton. When I passed each image by itself not using an array, it worked fine, but I want to randomize the image locations so I thought passing the array would be the way to go. Any help would be greatly appreciated.
    Thanks, Chad

    If you want to use those images in JButton, so use the ImageIcon arrays like this:
    MemoryApplet
    // declare ImageIcon array
    ImageIcon[] imgArr = new ImageIcon[6];
    for(int i = 0;i<6;i++)
      // create new ImageIcon
      // path: path of images
      imgArr[i] = new ImageIcon(path + "img" + i + ".jpg");
    // initialize MemoryGame instance and call method
    icon = new MemoryGame();
    icon.setTheIcons(imgArr);Hope this help
    Liwh

  • Passing an array to a method taking an Object?

    Hi,
    I need to pass an array of randomly generated numbers to a method that takes an Object.
    I can't seem to figure out how to do this...
    Here is my code for creating the array of random numbers:
    Random generator = new Random();
    for (int i = 0; i < size; i++)
    a[ i ] = generator.nextInt();
    mySort(a);
    Here is the signature of the method I am trying to pass it to:
    public static void mySort(Comparable [] a)
    When I compile I get the following message: mySort ( java.lang.Comparable[] ) cannot be applied to (int[]) mySort(a);
    How can I convert the array into an Object?
    Any help is much appreciated!

    >
    It'll be easier in java 1.5...But will result in terrible code being written by folks who don't understand the penalties incurred with auto-boxing.
    If you have to sort an array of integers, grab a QuickSort implementation that works with int[] directly (there is one built into the Arrays class) - creating all of those temporary objects kills performance.
    - K

Maybe you are looking for