Populate an arraylist....

Hi guys,
i'm a new java user and i have a big question for you.
I'm developing a jsf application with eclipse and i have a problem.
I have to import a txt file with this format
string string string string
string double double double
string double double double
string double double double
etc....
The file is composed by a first row that has 4 columns of string type
and other rows of 4 columns with first column string and the others double.
I have to define 2 object, a first headline object that is an array of string, for storing the first row, and a second object that is composed by a string field and by an array of double.
Headline string[]=new string[4];
            public class row{
                 String geneid=null;
                 values double[]=null;
            public void row(String idGene,double[3] x ) {
                this.geneid=idPr;
                this.values=x;
              }This code is correct?
For storing my file i need an headline array of string and an arraylist of row objects.
How can populate them with the txt file?
I've loaded the file with
BufferedReader br = new BufferedReader(new InputStreamReader(myFile.getInputStream())); Can you help me with some code?I'm not expert....

This is not a JSF question. Please put your question on New to Java Programming or in Java Programming forum

Similar Messages

  • Arraylist.toString (need to count amount of a specific character in a list)

    hi
    I have a sql query that im using to populate a ArrayList<String>. I need to count the amount of "+" symbols in the all of the list. My first idea was to use Arraylist.toString and then run the resulting string through this method
    public static int countMsgs(String result){
              int counter = 0;
              for(int i=0;i<result.length();i++)
                        if(result.charAt(i)=='+')
                        counter++;                                      
              return counter;However when I do this:
    ResultSet userid1021result = sql.executeQuery
          ("select address from MESSAGES where SENT_TIME >=  '" + start + " 00:00:00' AND SENT_TIME <= '"+ end + " 23:59:59' "
          + "and USER_ID = 1");
          while (userid1021result.next()) {
                  String addresses = userid1021result.getString("address");
                  userid1021.add(addresses);
          String blah = userid1021result.toString();
          System.out.println(blah);It outputs "com.mysql.jdbc.JDBC4ResultSet@1abc7b9" which is obviously not what i was expecting
    How do i get the contents of the arraylist into one big string so I can run it through my countMsgs method?
    Thanks

    Guys,
    Where a, b, and c are strings: plusesIn(a) + plusesIn(b) + plusesIn(c) == plusesIn(a+b+c)
    Ergo, concatenating the strings is just a waste of time.
    Also... I'd factor out the character-to-find from countMsgs to make a static helper method (in a "reusable" StringUtils class)...
    * Returns the number of times target occurs in string
    public static final int occurences(String string, char target) {
      int count = 0;
      for ( char c : s.toCharArray() ) { // 1.6 only
        if( c == target ) count++;
      return target;
    }

  • How to populate Global Container

    Hi,
         We have an output structure of the form-
        <Record>                          occurence 1-n
            <MSGFN>..</MSGFN>  occurence 1-1
            <MTART>..</MTART>    occurence 1-1
            <VOLUM>..</VOLUM>   occurence 1-1
        </Record>
    I have written a UDF(queue) to populate the Record field. In this UDF I want to populate an ArrayList (ArrayList as initial size is unknown) with the output queue of Record which I need to reference in other another UDF(queue) for populating the fields under Record.
    When I tried this by declaring an ArrayList under Global Variables and then trying to use that ArrayList in the UDFs for populating the fields, it was unable to do so.
    Can anyone help out with this?

    Hi;
    This is all abt Global Variables
    <b>Global Variables Declaration</b>
    ArrayList arrVI;
    int counter =0;
    <b>Initialization Section</b>
    arrVI= new  ArrayList();
    <b>assignment</b>
    arrVI.add(sVI[iLoopCounter]);
    counter++;
    <b>Calling Back</b>
    for (int i =0;i<counter;i++)
    result.addValue(arrVI.get(i)+"");
    Mudit
    Award points if it helps

  • Populate Array from Database!

    I have this working manually, but please need help creating this from a DB Connection and populating the Array with the results.
    I just need help with populating "DestinationItem[]" from the SQL below
    DestinationBean.java
    //  Manual Array works but I need this to be populated from DB using the below Query and DB Connection info.
        private DestinationItem[] destinationResults = new DestinationItem[]{
                new DestinationItem("58285", "Dodge Grand Caravan"),
                new DestinationItem("57605", "Dodge SX 2.0"),
                new DestinationItem("58265", "Chrysler 300 Touring")
        public DestinationItem[] getdestinationResults() {
            return destinationResults;
        public class DestinationItem {
            String destid;
            String commdefid;
            public DestinationItem(String destid, String commdefid) {
                this.destid = destid;
                this.commdefid = commdefid;
    // Getter/Setter below
    // END
    I need to take this DB Connection Logic and populate the "DestinationItem[]" Array above and I need help.
    //DBConnection
    public static ArrayList<CustomerBean> getCustomer() {
            try {
                Class.forName("oracle.jdbc.OracleDriver").newInstance();
                Connection con = DriverManager.getConnection("jdbc:oracle:thin:", "BLAH", "BLAH");
                PreparedStatement ps = con.prepareStatement("select destination_id, commdef_id from BLAH.destination");
                ArrayList<CustomerBean> al = new ArrayList<CustomerBean>();
                ResultSet rs = ps.executeQuery();
                boolean found = false;
                while (rs.next()) {
                    CustomerBean e = new CustomerBean();
                    e.setDestId(rs.getString("destination_id"));
                    e.setDestId(rs.getString("commdef_id"));
                    al.add(e);
                    found = true;
                rs.close();
                if (found) {
                    return al;
                } else {
                    return null; // no entires found
            } catch (Exception e) {
                System.out.println("Error In getCustomer() -->" + e.getMessage());
                return (null);

    I have this working manually, but please need help creating this from a DB Connection and populating the Array with the results.
    What does 'working manually' mean?
    What PROBLEM are you having? The code you posted appears to ALREADY populate an ArrayList with the results.
    I just need help with populating "DestinationItem[]" from the SQL below
    Are you asking how to convert the ArrayList returned by the'getCustomer' method into an array?
    Just use the 'toArray' method of ArrayList. See the Java API
    ArrayList (Java Platform SE 7 )
    public Object[] toArray()
    Returns an array containing all of the elements in this list in proper sequence (from first to last element). 
    The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array. 
    This method acts as bridge between array-based and collection-based APIs.
    Why do you have one class named DestinationBean' and another one just like it named 'CustomerBean'?
    I need to take this DB Connection Logic and populate the "DestinationItem[]" Array above and I need help.
    What is it you need help with?
    The 'getCustomer' method ALREADY populates an ArrayList. So just convert the ArrayList to an array using 'toArray'.
    public static ArrayList<CustomerBean> getCustomer() {
    I don't understand what problem you are having.
                Class.forName("oracle.jdbc.OracleDriver").newInstance();
    Remove that line - that hasn't been used for years.  
                boolean found = false;
    Remove that code and ALL references to 'found'. You created an empty ArrayList when you started. If it is still empty when you are done then there are NO results. Just return an empty array (preferable).
    Let the caller handle an empty ArrayList.
    You already have code that appears to get a collection of items.
    Explain EXACTLY what your problem is. Why can't you just use the code you posted?

  • Populating an ArrayList of ArrayList

    Hi,
    Could anyone pls help me with this one. I'm trying with the following code to populate an ArrayList (alDataRows) which contain several ArrayLists(alCols). variable rsResultSet is the resultset from which I want to populate this arraylist and variable intNumberOfColumns is the number of columns I have in that resultset.
    What's happening is that, finally, I'm getting the last record only in this arraylist. Also, if I don't do alCols.clear(), alCols is having (number of columns * number of rows) records which is erroneous.
    Could somebody pls correct me.
    thanks much in advance!
    =====================
    ArrayList alCols = new ArrayList();
    ArrayList alDataRows = new ArrayList();
    int intRowPos = 0;
    while (rsResultSet.next())
    alCols.clear();
    for (int i=0; i < intNumberOfColumns ; i++)
         alCols.add(i, rsResultSet.getString(i+1));
    alDataRows.add(intRowPos,alCols);
    intRowPos++;
    //System.out.println("intRowPos = " +intRowPos);
    }

    Could anybody pls help me on this one?
    I have the following to populate an arrylist(alDataRows) of arraylists(alCols).
    ArrayList alCols = null;
    ArrayList alDataRows = new ArrayList();
    int intRowPos = 0;
    while (rsResultSet.next())
    alCols = new ArrayList();
    for (int i=0; i < intNumberOfColumns ; i++)
    {      alCols.add(i, rsResultSet.getString(i+1));  
    alDataRows.add(intRowPos,alCols);
    intRowPos++;
    Now how do I retrieve a particular value within it?
    Is it like (String)alDataRows.get(rowindex).get(colindex).
    This is not compiling.
    thanks much

  • Formating the response of Java webservice to table structure in webdynpro

    Hi All,
    I am stuck at a point where I have  a Java Webservice resulting an ArrayList Response.
    My webdynpro will have to populate the ArrayList response into a table.
    Below is the piece of code am using to execute my webservice.
    CODE :
    JavajdbcModel md = new JavajdbcModel();
        Request_Display reqDisp= new Request_Display(md);
        try
        reqDisp.execute();
        wdComponentAPI.getMessageManager().reportSuccess("Str: "+reqDisp.getResponse());
    RESULT :
    <modelObject class="Response_Display"><target roleName="DisplayResponse"><modelObject class="DisplayResponse"><attribute name="Response" value="[[i01111, USSS, DSGTechTwo, DEF], [i012345, USSS, DSGTechOne, ABC], [i067890, USSS, DSGTechTwo, DEF], [i07777, USSS, DSG, ggg], [i08888, cccc, vvvv, bbbb], [io3333, USSS, DSGTechOne, abc]]"/></modelObject></target></modelObject>
    The required output are the values that are with the blue font above.
    I have tried with methods like :
    getAttributeValue, getResult - but are of not much help.
    Could you please help me out in this.
    Thanks & Regards,
    Suyukti. B N.

    Dear Suyukti,
    Since your web service returns an arraylist,
    you need to retreive the response into an arraylist. Then you can you this arraylist to populate the node for the table as required.
    Your code will be something like
    ArrayList al = (ArrayList)reqDisp.getResponse();
    Now that you have the response, then use the get function of the arraylist to set the context.
    al.get(index);
    This function returns  java.lang.Object, so you need to to cast into the required type.
    e.g. String str = (String) al.get(0);
    Hope that works.
    Regards,
    Mayuresh.
    PS: xxxxxxxxxxxxxxxxxxxxxxxxxx
    Edited by: Armin Reichert on Jan 1, 2008 3:49 PM

  • Moving items up and down in a JList

    Hello I posted this query in the wrong forum and so now I am trying to correct the problem Here is the link
    http://forum.java.sun.com/thread.jspa?threadID=5267663&tstart=0
    Hi-
    I have a problem with moving selected items up and down in a JList..
    When I select an item in the JList and press ctrl + (the up or down arrow key),
    I want the selected item to move up (or down).
    My code works. That is to say it does what I want, only the highlighted item does not correspond to the selected item.
    When I move an item up I would like it to remain selected, which I guess it is as repeated moves will move the item.
    But it does not appear to be working. because the highlight is above the selected item when moving up and below the selected item when moving down.
    Here is my code:
    public class MyClass  implements MouseListener,KeyListener
    private JList linkbox;
    private DefaultListModel dlm;
    public List<String> Links= new ArrayList<String>();
    private String Path;
    private JScrollPane Panel;
        public MyClass  (String path,JScrollPane panel){
        super();
            Path=path;
            Panel=panel;
    //Populate the ArrayList "Links" etcetera.
         dlm = new DefaultListModel();
            linkbox = new JList(dlm);
            for(int k=0;k<Links.size();k++){
                dlm.addElement(Links.get(k));
        public void keyPressed(KeyEvent e) {
        System.out.println("You pressed "+e.getKeyCode());
           if(e.getKeyCode()==38&&e.getModifiers()==KeyEvent.CTRL_MASK){
            Link sellink =linkbox.getSelectedValue();
                MoveUP(sellink);
            if(e.getKeyCode()==40&&e.getModifiers()==KeyEvent.CTRL_MASK){
                Link sellink =get(linkbox.getSelectedValue();
                MoveDown(sellink);
    private void MoveUP(Link link){
        int pos=-1;
        for(int p=0;p<Links.size();p++){
            Link l=Links.get(p);
            if(l.indexOf(link)==0){
            pos=p;
            break;
        if(pos!=-1&&pos>0){
            Links.remove(link);
            Links.add(pos-1,link);
            dlm.removeAllElements();
            for(int k=0;k<Links.size();k++){
            dlm.addElement(Links.get(k));
            Panel.setViewportView(linkbox);
            linkbox.setSelectedIndex(pos-1);
        private void MoveDown(Link link){
            int pos=-1;
            for(int p=0;p<Links.size();p++){
                Link l=Links.get(p);
                if(l.indexOf(link)==0){
                pos=p;
                break;
            if(pos!=Links.size()-1&&pos>0){
            System.out.println("pos= "+pos);
                Links.remove(link);
                Links.add(pos+1,link);
                dlm.removeAllElements();
                for(int k=0;k<Links.size();k++){
                dlm.addElement(Links.get(k));
                Panel.setViewportView(linkbox);
                linkbox.setSelectedIndex(pos+1);
        }And here is a compileable version...
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.UIManager;
    class MoveableItems  implements KeyListener
         private JList jlist;
         private List<String> items = new ArrayList<String>();
         private DefaultListModel dlm;
         private JScrollPane sp;
         public MoveableItems(){
             JFrame f = new JFrame();
           items.add("Fox");
           items.add("Hounds");
           items.add("Cart");
           items.add("Horse");
           items.add("Chicken");
           items.add("Egg");
             dlm = new DefaultListModel();
            jlist = new JList(dlm);
             KeyListener[] kls=jlist.getKeyListeners();
             for(int k=0;k<kls.length;k++){
                 jlist.removeKeyListener(kls[k]); 
             jlist.addKeyListener(this);
             for(int k=0;k<items.size();k++){
                dlm.addElement(items.get(k));
              sp = new JScrollPane();
                sp.setViewportView(jlist);
             f.getContentPane().add(sp);
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             f.setSize(650, 250);
             f.setVisible(true);
         public static void main(String[] args)
             try{
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                }catch(Exception e){System.out.println(e.getMessage());}
             new     MoveableItems();
        public void keyPressed(KeyEvent e) {
        System.out.println("You pressed "+e.getKeyCode());
            if(e.getKeyCode()==38&&e.getModifiers()==KeyEvent.CTRL_MASK){
            String selString =(String)jlist.getSelectedValue();
                MoveUP(selString);
            if(e.getKeyCode()==40&&e.getModifiers()==KeyEvent.CTRL_MASK){
                String selString =(String)jlist.getSelectedValue();
                MoveDown(selString);
        public void keyReleased(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
    private void MoveUP(String link){
        int pos=-1;
        for(int p=0;p<items.size();p++){
            String l=items.get(p);
            if(l.indexOf(link)==0){
            pos=p;
            break;
        if(pos!=-1&&pos>0){
            items.remove(link);
            items.add(pos-1,link);
            dlm.removeAllElements();
            for(int k=0;k<items.size();k++){
            dlm.addElement(items.get(k));
            sp.setViewportView(jlist);
            jlist.setSelectedIndex(pos-1);
            jlist.requestFocus();
        private void MoveDown(String link){
            int pos=-1;
            for(int p=0;p<items.size();p++){
                String l=items.get(p);
                if(l.indexOf(link)==0){
                pos=p;
                break;
            if(pos<items.size()){
            System.out.println("pos= "+pos);
                items.remove(link);
                items.add(pos+1,link);
                dlm.removeAllElements();
                for(int k=0;k<items.size();k++){
                dlm.addElement(items.get(k));
                sp.setViewportView(jlist);
                jlist.setSelectedIndex(pos+1);
                jlist.requestFocus();
    }Now for some reason this works better.
    I notice that the highlight does follow the selection but there is also something else there.
    Still in my original version the highlight seems to appear where the dotted lines are?
    There seems to be dotted lines around the item above or below the selected item (depending on whether you are going up or down).
    Any thoughts at this point would be appreciated.
    -Reg.
    Can anyone explain to me why this is so and if it can be fixed?
    If any one can help I would be grateful,
    -Reg

    You seem to be making a genuine effort. Key Bindings like anything else involves getting familiar with the code and the idiosyncrasies involved and just playing with the code yourself. To get you started, if the JList were called myList I'd do something like this for the up key:
            KeyStroke ctrlUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.CTRL_DOWN_MASK);
            myList.getInputMap().put(ctrlUp, "Control Up");
            myList.getActionMap().put("Control Up", new AbstractAction()
                public void actionPerformed(ActionEvent e)
                    // do stuff to move your item up
            });Please read the tutorial for details, explanation, etc...

  • The Managed Bean in the faces-config.xml File

    I am still very new to JSF. I am confused about the managed bean.
    For example, I have a button in my web page. A click on this button invokes an action; say, ListAction.java.
    In this ListAction class, I instantiate a business delegate; say, ListPersonnel.java and call a method in this business delegate to return an ArrayList: personnel. Of course, this business delegate goes through facade, DAO, etc. to populate the ArrayList. This ArrayList is a collecation of a JavaBean called PersonnelBean that gets and sets a number of personnel information; such as ssn, name, etc.
    Upon this ArrayList is successfully populated and received by the ListAction class, I am going to display a web page with a table. In JSF, it is <h:dataTable ...>.
    My questions are regarding the managed bean in the faces-config.xml file.
    1. Which one is my <managed-bean-class>? packageName.ListAction? or packageName.PersonnelBean? or something else?
    2. What should be my <managed-bean-name>? I guess that I can give a name I like. Is it right? What about xyz?
    3. Then, how do I specify the "value" attribute of my <h:dataTable ...> tag when I display a web page to show the data table? Is it correct to specify value="#{xyz.personnel}"? What is the correct specification if it is wrong?
    4. I guess that I can give any name to the "var" attribute in the <h:dataTable ...> tag. Is it right?

    1. Which one is my <managed-bean-class>?
    packageName.ListAction? or
    packageName.PersonnelBean? or something else?ListAction
    2. What should be my <managed-bean-name>? I guess
    that I can give a name I like. Is it right? What
    about xyz?Anything you like. xyz is OK.
    3. Then, how do I specify the "value" attribute of my
    <h:dataTable ...> tag when I display a web page to
    show the data table? Is it correct to specify
    value="#{xyz.personnel}"? What is the correct
    specification if it is wrong?xyz.personnel is OK assuming that ListAction class has a public
    method getPersonnel() which returns the ArrayList of PersonnellBeans.
    4. I guess that I can give any name to the "var"
    attribute in the <h:dataTable ...> tag. Is it right?Yes, you can give any name you like.

  • Dropdown and lifecycle

    I've been testing a very simple page with a dropdown list which is bounded to an ArrayList, a button to display "hello" and an outputtext where the "hello" string will be displayed. The dropdown selectitems value is bounded to the arraylist. The arraylist is populated in the constructor of the page bean. There are no errors, everything runs smoothly. The dropdown list box is populated. However, my button that will just display a hello world on a outputtext control is never reached. I 've used the LifeCycleStudy (http://developers.sun.com/prodtech/javatools/jscreator/reference/sampleapps/2004q2/lifecycleStudy.zip) sample application to see if the event handler for the button is reached.. unfortunately it is not. why is it so? if removed the last three lines of the code below(listJournals.add...) it will work just fine... Where should i place the initialization of the dropdown?
    by the way, this is are the code added at the LifeCycleStudy in page1's constructor to populate the arraylist.
    listJournals = new ArrayList();
    listJournals.add(new SelectItem(new Integer(1),"TEST 1"));
    listJournals.add(new SelectItem(new Integer(2),"TEST 2"));
    listJournals.add(new SelectItem(new Integer(3),"TEST 3"));
    thanks!

    By the way....these are the events that are missing when i added the dropdown list... this proves that the button1_action eventhandler is never called...
    (from the server.log)
    |WebModule[lifecyclestudy]Page1.java - inside beforeUpdateModelValues HELLOWORLD|#]
    |WebModule[lifecyclestudy]Page1.java - inside beforePhase|#]
    |WebModule[lifecyclestudy]Page1.java - inside afterUpdateModelValues HELLOWORLD|#]
    |WebModule[lifecyclestudy]Page1.java - inside afterPhase HELLOWORLD|#]
    |WebModule[lifecyclestudy]Page1.java - inside beforeInvokeApplication HELLOWORLD|#]
    |WebModule[lifecyclestudy]Page1.java - inside beforePhase|#]
    |WebModule[lifecyclestudy]Page1.java - inside button1_action, posting back to Page1 HELLOWORLD|#]
    |WebModule[lifecyclestudy]Page1.java - inside afterInvokeApplication HELLOWORLD|#]
    it's really weird... if i removed the codes that will add SelectItem in the list the event handler will be called... :(

  • Programitically creating column series to flex chart not showing the chart

    I want to create n number of series dynamically when i run my
    application.
    where n can be any value it depends on the data which i
    retrieve from database. below i pasted the example
    ( in this example i have taken n = 4 i.e., CountMax=4 if i
    change the CountMax=6 then it should generate 6series dynamically
    after calculating the values. ). just copy the below code and paste
    it in Flex builder and run the application.
    in this example i am facing problem, chart series are not
    showing. i dont know the reason why its not showing, if anyone got
    the solutions for the problem please let me know. my actual
    requirement is to retrieve data from Salesforce account and want to
    populate the arraylist then display the chart.
    <?xml version="1.0"?>
    <!-- Example showing using mx:LineSeries vs using AS to
    create chart series programmatically -->
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="drawChart()" layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.charts.series.ColumnSeries;
    import mx.charts.series.LineSeries;
    import mx.collections.ArrayCollection;
    [Bindable]
    public var categoryArray:ArrayCollection = new
    ArrayCollection();
    [Bindable]
    public var sArray:ArrayCollection = new ArrayCollection();
    public function drawChart():void
    var histMax:int = 25;
    var histMin:int = 5;
    var countMax:int = 6;
    var tmpArr:Array = new Array();
    categoryArray.removeAll();
    for(var n:int = 0; n < 10; n++)
    tmpArr[n] = histMin + Math.round((2 * n) / 20 * (histMax -
    histMin));
    categoryArray.addItem({data:tmpArr[n]});
    // Add a series to the chart with the x-values and y-values
    // from the arrays and set the series type to a column chart
    for(var chartSeries:int = 0; chartSeries < countMax;
    chartSeries++)
    var tmpseries:Array = new Array(10);
    for(var i:int = 1; i < 10; i++)
    tmpseries = 3 * Math.random();
    var cs:ColumnSeries = new ColumnSeries();
    columnchart1.series.join( = [cs];
    sArray.addItem({data:tmpseries});
    //columnchart1.dataProvider = sArray;
    cs = new ColumnSeries();
    cs.dataProvider= sArray;
    cs.displayName = 'Series';
    cs.yField = 'data';
    columnchart1.series[chartSeries] = cs;
    ]]>
    </mx:Script>
    <mx:Panel title="Dynamic Series Adding Sample"
    width="195%" height="90%" layout="absolute">
    <mx:ColumnChart id="columnchart1" height="338"
    width="396" showDataTips="true" type="stacked" x="10" y="0">
    <mx:horizontalAxis>
    <mx:CategoryAxis dataProvider="{categoryArray}"
    categoryField="data"/>
    </mx:horizontalAxis>
    <mx:verticalAxis>
    <mx:LinearAxis baseAtZero="true" maximum="3"
    autoAdjust="true"/>
    </mx:verticalAxis>
    </mx:ColumnChart>
    </mx:Panel>
    </mx:Application>

    <?xml version="1.0"?>
    <!-- Example showing using mx:ColumnSeries vs using AS to
    create chart series programmatically -->
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="drawChart()" layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.graphics.SolidColor;
    import mx.charts.HitData;
    import mx.controls.Alert;
    import mx.charts.series.ColumnSeries;
    import mx.charts.series.LineSeries;
    import mx.collections.ArrayCollection;
    [Bindable]
    public var categoryArray:ArrayCollection = new
    ArrayCollection();
    public function drawChart():void
    var histMax:int = 25;
    var histMin:int = 5;
    var countMax:int = 3;
    var tmpArr:Array = new Array();
    categoryArray.removeAll();
    for(var n:int = 0; n < 10; n++)
    tmpArr[n] = histMin + Math.round((2 * n) / 20 * (histMax -
    histMin));
    categoryArray.addItem({data:tmpArr[n]});
    var cs:ColumnSeries = new ColumnSeries();
    columnchart1.series = [cs];
    // Add a series to the chart with the x-values and y-values
    // from the arrays and set the series type to a column chart
    for(var chartSeries:int = 0; chartSeries < countMax;
    chartSeries++)
    var tmpseries:Array = new Array(10);
    for(var i:int = 0; i < 10; i++)
    tmpseries
    = 1 * Math.random();
    if(tmpseries > 0.5)
    tmpseries
    = 1;
    else
    tmpseries = 0;
    var testArrCol:ArrayCollection = new ArrayCollection();
    for(var j:int =0; j < 10; j++)
    var m:Number = tmpArr[j];
    var m1:Number = tmpseries[j];
    testArrCol.addItem({mData:m.toString(),nData:m1.toString()});
    cs = new ColumnSeries();
    cs.dataProvider = testArrCol;
    cs.displayName = 'Series' + chartSeries;
    cs.xField = 'mData';
    cs.yField = 'nData';
    columnchart1.series[chartSeries] = cs;
    public function myTipFunction(hitData:HitData):String
    return(ColumnSeries(hitData.element).displayName +" - "+
    hitData.item.mData + "\n" + "Value : "+ hitData.item.nData);
    ]]>
    </mx:Script>
    <mx:Panel title="Dynamic Series Adding Sample" width="98%"
    height="90%" layout="absolute">
    <mx:ColumnChart id="columnchart1" height="338"
    width="396" showDataTips="true" type="stacked" x="10" y="0"
    dataTipFunction="{myTipFunction}">
    <mx:horizontalAxis>
    <mx:CategoryAxis dataProvider="{categoryArray}"
    categoryField="data"/>
    </mx:horizontalAxis>
    <mx:verticalAxisRenderer>
    <mx:AxisRenderer visible="false"/>
    </mx:verticalAxisRenderer>
    </mx:ColumnChart>
    </mx:Panel>
    </mx:Application>

  • How to get result of querry independet of a datatype?

    Hi All!
    I try to write a program, that calls stored procedures in a database independent of a name and arguments list. To get a result of a query I must call one of the functions getInt(), getString() etc. of CallableStatement. I'd like to write a wrap function, for instance getResult(), that get the result independent of the result's type. Has anybody any idea, how I can do it?
    Any help will be appreciate.
    Regards,
    Andrej.

    Hi Justin,
    Even we have been writing a kind of these generic methods to send a query to database, fetch the Resultset and then populate an ArrayList with the Resultset data.
    What do you get out of this ?
    -> Less code to maintain
    -> Single point of access to datasource
    -> JDBC Code reuse
    i agree that it might cost some cpu cycles in populating an ArrayList and then doing the casting again. But isn't it worth all the above credits.
    An example of such a method is
      public ArrayList execute( String query, ArrayList params )
                    throws SQLException {
        Connection con = null; // Database Connection object
        ArrayList rowset = new ArrayList();
        try {
          // Get the Database Connection
          con = connector.getConnection();
          // Use PreparedStatement object to execute the SQL Query
          PreparedStatement pst = con.prepareStatement( query );
          // Bind the columns values from the ArrayList object
          if( params != null ) {
            for( int i = 0; i < params.size(); i++ ) {
              pst.setObject( i + 1, params.get( i ) );
          // Execute the Query to get the ResultSet object
          ResultSet rst = pst.executeQuery();
          // Get column count from ResultSet Metadata
          int colCount = rsmtdt.getColumnCount();  // This may not be the correct syntax
          // Populate ArrayList
          while(rset.next()) {
            ArrayList row = new ArrayList();
         for(int i=1;i<=colCount;i++)
           row.add(rset.getObject(i);
         rowset.add(row);
          // Close the ResultSet and Statement
          rst.close();
          pst.close();
        } catch( SQLException ex ) {
          throw new DBException( "Unable to execute the SQL Query in execute "+
                                     "method of DBBroker class of given status " +
                                 " : " + ex.getMessage() );
        } catch( Exception ex ) {
          throw new DBException( "Exception thrown in execute() method of " +
                                 "DBBroker class of given status : " +
                                  ex.getMessage() );
        } finally {
          try {
            connector.releaseConnection( con ); // Releases the connection
          } catch( DBConException ex ) {
            throw new DBException( "Unable to release the connection of given " +
                                   "status : " + ex.getMessage() );
        return rowset;
      }Regards
    Elango.

  • Getter is called multiple times

    Hi All,
    I my JSF page i am using one foreach which will read elements from an ArrayList. ArrayList is present in one PagesFlowSope-Bean.
    I am facing problem that, the getter for ArrayList is called multiple times.I want to restrict that,is there any way for doing this.
    Thanks in advance,

    Your getter gets called every time the component/page gets rendered/refreshed. If you feel that it refreshes too many times, check the partial triggers on that component or its parent. Just a thought, to avoid any logic getting called in your getter multiple times, if possible, put a empty or null check on your attribute and initialize it only if it is null/empty. In that way even if it gets called multiple times your logic to populate your ArrayList doesn't fire everytime.
    Good luck !

  • Drop Down list issues in jsp

    Hi,
    I am facing an issue with drop down list in jsp pages on page postback. Let me explain in detail. I have a client.jsp page which has a drop down list and a text box. The drop down list is populated from an Action class (lets say testAction.java). In the client action form class there is a validation which requires the user to enter some value in the text box.
    So here is the problem, when the client.jsp page loads, the drop down list is populated perfectly, but then the user clicks submit button without entering anything in the textbox, the page loads again with an error message ("Please enter some value in the textbox"). At this point the drop down list does not contain any value. Any ideas what could I do?
    I am posting the code here for individual pieces,
    Struts-config.xml_
    <action path="/client" type="com.myapp.struts.testAction" scope="session">
    <forward name="success" path="/createClient.jsp"/>
    </action>
    <action input="/createClient.jsp" name="ClientActionForm" path="/createClient" scope="session" type="com.myapp.struts.ClientAction">
    <set-property property="cancellable" value="true" />
    <forward name="success" path="/loginSuccessful.jsp"/>
    <forward name="cancel" path="/Welcome.do"/>
    </action>
    index.jsp_
    <h5><html:link action="/client" styleClass="purplelink">Create a new client</html:link></h5>
    testAction.java_
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {
    ArrayList<String> arrList = new ArrayList<String>();
    arrList.add("sports");
    arrList.add("music");
    arrList.add("test 1");
    arrList.add("test2");
    request.setAttribute("mylist", arrList);
    return mapping.findForward(SUCCESS);
    createClient.jsp_
    <select name="droplist">
    <c:forEach var="itemName" items="${mylist}">
    <option><c:out value="${itemName}" /></option>
    </c:forEach>
    </select>
    <html:text property="clientName" />
    ClientActionForm_
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
    ActionErrors errors = new ActionErrors();
    if (getclientName() == null || getclientName().length() < 1) {
    errors.add("name", new ActionMessage("error.name.required"));
    return errors;
    Here is the process/page flow.
    index.jsp is the first page which is loaded.
    Link on index.jsp calls action="/client"
    This pulls mapping from struts-config and calls testAction.java
    This populates the arraylist and returns to the createClient.jsp page (mapping from struts-config.xml)
    Now createClient.jsp page has two fields (dropdown list and textfield=clientName) and a submit button
    if user clicks submit, clientActionForm is called and does not enter anything into clientName text field, error message is returned.
    At this point, the drop down list in createClient.jsp is not populated and is returned as empty, even though the scope=session in struts-config.xml
    Please provide some inputs on how can I handle this issue.
    Thanks
    Ashish

    I think one solution would be instead of putting the list in the request, but it in your ActionForm.
    Add a field to the ClientActionForm with getters and setters.
    Then change your action.
    ArrayList<String> arrList = new ArrayList<String>();
    arrList.add("sports");
    arrList.add("music");
    arrList.add("test 1");
    arrList.add("test2");
    ClientActionForm frm = (ClientActionForm)form;
    frm.setMyList(arrList);
    return mapping.findForward(SUCCESS);

  • How to call a method on click of selectOneChoice dropdown box

    Hi,
    I am using selectOnceChoice whose list is coming from an arrayList.
    On the load of my page, I am populating the arrayList and it is getting visible in the selectOneChoice dropdown.
    But I have a scenario where I need to populate the arrayList(List Items) for selectOnceChoice on click of selectOnceChoice box. Not at the time of page load.
    I tried to do that with the help of clientListener and ServerListener but it seems that it is ServerListener is not the child attribute of selectOnceChoice.
    Can anyone please help me out to perform or call a method on click of selectOnceChoice box.
    Thanks,
    Vicky

    Could someone please explain to me the main difference between adapters and listeners? WindowListener is an interface, if you use it then you have to implement all its methos whether you use then or not while WindowAdapter is a class which implements WindowListener and provides empty implementations of all the methods in the listener, so basically by using windowAdapter you are avoiding
    the implementation of methods which you don't required.

  • Bean composing another Bean

    Hi,
    I am having a page that displays both search and searchResults in two different containers. I am trying to do them with one bean and one jsp. (Thats how my current implementation is with JSPs -If the results are there, then I display the results container).
    I ma not quite understood how to do this with faces. I have a bean having several strings defining search criteria and an arryalist of SearchResult Objects. When the search form is submitted, I am calling a search action in the bean that populates the arraylist. I am not quite sure, how to display this arraylist.
    My Question is: ArrayList is list of objects and how to display them in JSP in a table format...?

    Hi,
    I am having a page that displays both search and
    and searchResults in two different containers. I am
    trying to do them with one bean and one jsp. (Thats
    how my current implementation is with JSPs -If the
    results are there, then I display the results
    container).
    I ma not quite understood how to do this with faces. I
    have a bean having several strings defining search
    criteria and an arryalist of SearchResult Objects.
    When the search form is submitted, I am calling a
    search action in the bean that populates the
    arraylist. I am not quite sure, how to display this
    arraylist.
    My Question is: ArrayList is list of objects and how
    to display them in JSP in a table format...?
    The <h:data_table> component tag is designed for this sort of thing.
    Let's assume your list of SearchResult beans can be retrieved by calling the getSearchResults() method of a managed bean created with the name mybean, and that each SearchResult bean has "accountId" and "name" properties. You might display them like this:
      <h:data_table value="#{mybean.searchResults}" var="row">
        <h:column>
          <f:facet name="header">
            <h:output_text value="Account Id"/>
          </f:facet>
          <h:output_text id="accountId" value="#{row.accountId}"/>
        </h:column>
        <h:column>
          <f:facet name="header">
            <h:output_text value="Customer Name"/>
          </f:facet>
          <h:output_text id="name" value="#{row.name}"/>
        </h:column>
      </h:data_table>In the <h:data_table> tag, the "value" expression points at a list or array of beans, and the "var" attribute defines the name of a request-scope attribute that will contain the data for the current row. Then, the component iterates over all the items in the array, and renders the components inside each column once per row. It's also possible to put input fields and commands on each row as well, in a manner similer to the "Repeater" example that is in the "Components Demo" shipped with the beta version of the JavaServer Faces reference implementation.
    Craig McClanahan

Maybe you are looking for

  • Problems with ShutdownHook and Windows Service

    Hi friends, I am facing a problem with the ShutdownHook when a Java program is run as a Windows Service. In the program I am having a Daemon Thread which will be run in an infinite while loop accoridng to a boolean variable. I have a shutdown hook al

  • Buyer Account, Welcome mail with password & LDAP related query

    Hi All We are facing an issue with the LDAP configuration while creating Buy  side users, please see below If anyone of you could help, please provide your contact details or a solution to overcome this Background We have installed SAP E-Sourcing 5.1

  • Dreamweaver and PhoneGap: How to Edit the Application Manifest for an Android app

    I successfully created an Android app using dreamweaver cs6 and the PhoneGap build service.  I submitted the app and it is live in Google Play.  The only problem is that the app is requiring all kinds of permissions from users that are not necessary

  • "No Network Connection" When Updating to IOS 5.0.1 in iTunes

    Hey, Been trying up update to the latest IOS 5.0.1 on my iPad and iPhone, on two different machines, but always get a "No Network Connection" when I try to download the update. I have a working Internet connection as all other apps on all my machines

  • Upgrading from 10 year old powerbook

    I have a ten year old powerbook & need a new machine. Is the basic new IMac going to seem like light years ahead of what I've been using or should I bump up the spec & hope that in another ten years I will consider it money well spent or wish that I'