Months_between problem

Hello all,
select add_months(to_date('30-may-2007'), 9) from dual;
I got 29-FEB-2008.
Then,
select months_between(to_date('29-FEB-2008'), to_date('30-may-2007'))
from dual;
I got 8.97, it is not exact 9 months.
I think it is related to leap year. But my codes need to get exact 9 months to date, I can't use round.
How should I do?
Thanks.

I think it is related to leap year. But my codes need
to get exact 9 months to date, I can't use round.No it is not releated to leap years. it is related to how the add_months function and the months_between functions works. The solution could be to use add_month, instead of months_between.
However I do not know excatly how to fit that into your requirement...
maybe something like this (looks a bit complicated):
select case when add_months(to_date('30-MAY-2007'), months_between(trunc(to_date('29-FEB-2008'),'MM'), trunc(to_date('30-MAY-2007'),'MM'))) = to_date('29-FEB-2008')
     then
          months_between(trunc(to_date('29-FEB-2008'),'MM'), trunc(to_date('30-MAY-2007'),'MM'))
     else
     -1
     end case          
from dual
;

Similar Messages

  • Get Months and Days -- Problem with months_between

    Hi,
    For a report, I need to convert days as months and days for eg 370 days as 12 months 5 days.
    I tried below query
    with t as (
    select
    maturity_date - value_date tenor
    from account_master)
    select
    trunc(mod(months_between(trunc(sysdate,'YYYY')+ tenor,trunc(sysdate,'YYYY')),30)) month,
    (trunc(sysdate,'YYYY')+tenor)-add_months(trunc(sysdate,'YYYY'),trunc(months_between(trunc(sysdate,'YYYY')+ tenor,trunc(sysdate,'YYYY')))) "day"
    from t
    And i am getting output as
    MONTH day
    11 30
    23 30
    11 30
    1 5
    11 30
    11 30
    11 30
    0 6
    11 30
    for Number of days
    TENOR
    365
    730
    365
    36
    365
    365
    365
    6
    365
    As you can see for 365 days i am getting Months as 11 and days as 30
    and for 730 days i am getting months as 23 and days as 30.
    I want 365 days as 12 months and 0 days.
    I think it is months_between function that is creating this problem.
    Can anyone suggest another way of accomplishing this?
    Thanks and Regards
    Amit Trivedi

    2008 is a leap year! so it's 366 days long. therefore, 365 days is really only 11 months and 30 days (if you start counting from Jan 01, which is what you are doing).
    so the number of months and days between is dependent on the starting date (consider a range of 30 days starting on Jan 01, Feb 01 (leap year), Feb 01 (non-leap year) and Apr 01).
    so:
    with t as (
    select maturity_date - value_date tenor, value_date d1 from account_master
    select
    trunc(months_between(d1+ tenor,d1)) months,
    d1+tenor - add_months(d1,trunc(months_between(d1+ tenor,d1),30)) days
    from t
    or better yet:
    select
    trunc(months_between(maturity_date,value_date)) months,
    maturity_date - add_months(value_date,trunc(months_between(maturity_date,value_Date))) days
    from account_master
    /

  • Joining/Selection problem...

    I have created this view:
    - First it selects the Lowest and Highest date which should be taken in DATES
    - Then it selects every first of the month between the Lowest and Highest date and stores that in MONTHS
    - Then it selects the ID, FirstOfTheMonth, (intakes UP TO FirstOfTheMonth), (Outgoing UP TO FirstOfTheMonth) from TWO tables without matching any id field...
    Now If I run the view in SQL Developer, it works nicely. If I use the view in Crystal Reports i get an error message saying a subquery returns more than 1 row...
    I have a feeling that my CALCULATIONS table is wrongly setup. The problem is that I need to select the PNM_AUTO_KEY from Parts_master and use this Key in the two subqueries... The way i did that is probably wrong.... My guessing is I should use a OUTER JOIN in stead of the way I did it now...?_
    CREATE OR REPLACE FORCE VIEW "VIEW_STOCK_COUNT" ("PNM_AUTO_KEY", "COUNT_DATE", "QTY_RECEIVED", "QTY_USED", "QTY_BALANCE") AS
    with
    DATES as
    (select (select min(REC_DATE) from STOCK) as FROM_DT, (select max(CHANGE_DATE) from STOCK_ADJUST) as TO_DT from DUAL),
    MONTHS as
    (select add_months(trunc(FROM_DT,'MM'),ROWNUM-1) as DT from DATES connect by ROWNUM <= months_between(TO_DT, FROM_DT)+1),
    CALCULATIONS as
    (select
    PNM.PNM_AUTO_KEY PNM_KEY,
    MONTHS.DT DT,
    NVL((select sum(stm.qty_rec) from stock stm WHERE STM.REC_DATE < MONTHS.DT AND STM.PNM_AUTO_KEY = PNM.PNM_AUTO_KEY GROUP BY pnm_auto_key),0) INCOMING,
    NVL((select sum(saj.qty_adj) from stock_adjust saj
    inner join stock stm on saj.stm_auto_key = stm.stm_auto_key
    inner join parts_master pnm on stm.pnm_auto_key = pnm.pnm_auto_key where SAJ.CHANGE_DATE < MONTHS.DT AND STM.PNM_AUTO_KEY = PNM.PNM_AUTO_KEY group by pnm_auto_key),0) OUTGOING
    from MONTHS, PARTS_MASTER PNM)
    SELECT
    CALCULATIONS.PNM_KEY PNM_AUTO_KEY, CALCULATIONS.DT COUNT_DATE,CALCULATIONS.INCOMING QTY_RECEIVED, CALCULATIONS.OUTGOING QTY_USED, (CALCULATIONS.INCOMING + CALCULATIONS.OUTGOING) QTY_BALANCE
    FROM
    CALCULATIONS;

    Hi,
    user574699 wrote:
    I have created this view:
    - First it selects the Lowest and Highest date which should be taken in DATES
    - Then it selects every first of the month between the Lowest and Highest date and stores that in MONTHS
    - Then it selects the ID, FirstOfTheMonth, (intakes UP TO FirstOfTheMonth), (Outgoing UP TO FirstOfTheMonth) from TWO tables without matching any id field...
    Now If I run the view in SQL Developer, it works nicely. If I use the view in Crystal Reports i get an error message saying a subquery returns more than 1 row...
    Sorry, I don't know anything about Crystal Reports. I would expect the view to be handled entirely by the database. What is the query that you're running when you get the error?
    Will Crystal Reports run a very simple query on this view?
    I have a feeling that my CALCULATIONS table is wrongly setup. The problem is that I need to select the PNM_AUTO_KEY from Parts_master and use this Key in the two subqueries... The way i did that is probably wrong.... My guessing is I should use a OUTER JOIN in stead of the way I did it now...?_That's easy to test. Replace the scalar sub-queries with literals, and see if Crystal Reports will run it.
    If not, that's not the problem.
    If you do decide to re-write the calculations sub-query, and you need help, post some sample data and what calculations should contain given that data.
    Could the WITH-clause be causing the problem? (Again, it's hard to see why the front-end tool would care how the view was defined.)
    It looks like you could use in-line views instead of WITH, if necessary.
    CREATE OR REPLACE FORCE VIEW "VIEW_STOCK_COUNT" ("PNM_AUTO_KEY", "COUNT_DATE", "QTY_RECEIVED", "QTY_USED", "QTY_BALANCE") AS
    with
    DATES as
    (select (select min(REC_DATE) from STOCK) as FROM_DT, (select max(CHANGE_DATE) from STOCK_ADJUST) as TO_DT from DUAL),
    MONTHS as
    (select add_months(trunc(FROM_DT,'MM'),ROWNUM-1) as DT from DATES connect by ROWNUM <= months_between(TO_DT, FROM_DT)+1),
    CALCULATIONS as
    (select
    PNM.PNM_AUTO_KEY PNM_KEY,
    MONTHS.DT DT,
    NVL((select sum(stm.qty_rec) from stock stm WHERE STM.REC_DATE < MONTHS.DT AND STM.PNM_AUTO_KEY = PNM.PNM_AUTO_KEY GROUP BY pnm_auto_key),0) INCOMING,
    NVL((select sum(saj.qty_adj) from stock_adjust saj
    inner join stock stm on saj.stm_auto_key = stm.stm_auto_key
    inner join parts_master pnm on stm.pnm_auto_key = pnm.pnm_auto_key where SAJ.CHANGE_DATE < MONTHS.DT AND STM.PNM_AUTO_KEY = PNM.PNM_AUTO_KEY group by pnm_auto_key),0) OUTGOING
    from MONTHS, PARTS_MASTER PNM)
    SELECT
    CALCULATIONS.PNM_KEY PNM_AUTO_KEY, CALCULATIONS.DT COUNT_DATE,CALCULATIONS.INCOMING QTY_RECEIVED, CALCULATIONS.OUTGOING QTY_USED, (CALCULATIONS.INCOMING + CALCULATIONS.OUTGOING) QTY_BALANCE
    FROM
    CALCULATIONS;Don't post unformatted code

  • Report 3.0 Problems

    i have 3 problems:
    1-How can i open a rep file without asking the user,password,and the database instance?
    2- months_between function (01-mar-2001,28-mar-2000) return 11.90 --->false it must be 12)
    3-when calling a report using run_product function in forms,an error appear in the report engine say :"can't retrieve a string from the report builder message file"

    1.for ur first question it is not clear from where u want to run rep file if it is from form then use run_product built in
    and ii u want to run it from command line then use HOST command.
    2.The result is vey well ok if u want to see 12 as the result then use last_day().
    3.for ur this problem check the path u have given for the report in parameter.
    good luck
    sanjay solanki

  • Problem with Date difference in OBIEE

    Hi,
    OBIEe- 10.1.3.4
    My exp: Beginner in OBIEE
    I have a requirement to calculate a policy age with the date columns from a policy table these are.
    The columns involved are as below:
    1. policy_effective_date alias EFD
    2.policy_start_date alias STD
    3.policy_expiry_date alias EXD
    so my functionality is based as below
    Policy Age = (CASE WHEN EFD > sysdate THEN trunc( months_between( STD, sysdate ) /12 )
    ELSE trunc( months_between(EXD, STD) /12 ) END)
    I have implemented the same in OBIEE as
    Policay Age= CASE WHEN CAST (EFD AS TIMESTAMP ) >
    CURRENT_DATE THEN TIMESTAMPDIFF( SQL_TSI_YEAR , CAST (STD AS TIMESTAMP ), CURRENT_DATE ) ELSE TIMESTAMPDIFF( SQL_TSI_YEAR , CAST (STD AS TIMESTAMP ),
    CAST (EXD AS TIMESTAMP )) END
    PROBLEM!!!!: I am having the following data in the database
    EFD=06-OCT-05
    STD=06-OCT-99
    EXD=06-OCT-06
    Ideally the answer should be 7 years that is 2006-1999= 7 years but instead it gives "-93 years " thats because it does a 06-99 =-93 years.
    Please can anyone suggest where and what Date conversion can I use in the OBIEE formula??

    Try with extract year from (date column ) , it may solve your problem...

  • Studying for 1Z0-051, months_between issue

    Hi guys I'm working through SQL Fundamentals I Exam Guide and exercise 4-3 runs this query:
    SELECT EMPLOYEE_ID, LAST_NAME, HIRE_DATE
    FROM EMPLOYEES
    WHERE MONTHS_BETWEEN('01-JAN-2000',HIRE_DATE)>100;
    Looking at my sample HR schema the earliest hire_date is 2001 so the results come back with nothing. However if I change the date to '01-JAN-1960' I still get nothing, is there a problem with the query?
    Many thanks
    Mike

    837287 wrote:
    Hi guys I'm working through SQL Fundamentals I Exam Guide and exercise 4-3 runs this query:
    SELECT EMPLOYEE_ID, LAST_NAME, HIRE_DATE
    FROM EMPLOYEES
    WHERE MONTHS_BETWEEN('01-JAN-2000',HIRE_DATE)>100;
    Looking at my sample HR schema the earliest hire_date is 2001 so the results come back with nothing. However if I change the date to '01-JAN-1960' I still get nothing, is there a problem with the query?
    Many thanks
    MikeIMHO it is inappropriate to ask about individual topics in this forum. IMHO It is better asked in the SQL forum. This forums is more about the infrastructure, processes and procedures of Oracle Certification.
    There are a couple of reasons for this. One is that discussion can lead toward exam questions being published. I have seen this happen on a number of occasions, sometimes the orignal is no really a problem ... then braindump extracts and copyright breach material is posted in the same or another thread.
    The other reason is that there are a really wide spread of oracle certifications, the 1z0-051 may well be one of hte most common certiifcation exams, but it is one of perhaps about a hundred or so certification exams offered.
    Also worth a check is : http://www.mhprofessional.com/product.php?isbn=0071597867
    NB: Having said that my bucket and shovel approach is when working with these things is not to rely on an implicit character to date conversion but to ensure I am using an explicit character to date conversion and see what happens with that.

  • PROBLEM IN GETTING MONTHLY OPENING & ENDING BALANCE BETEEN TWO DATES

    Hi,
    i m executing this query to get following result.
    OB is function through which i m getting Opening qty at time '01-JAN-2005' .
    QTYIN is qty purchased.
    QTYOUT is qty sold.
    END_BAL is difference of (OPENING_BALANCE+ QTYIN) - QTYOUT.
    PNAME is product name.
    SELECT ALL
    TO_CHAR(STKTRAN.SDATE,'MON,YY') MON,
    PRODUCTS.PNAME,
    OB(PID,'01-OCT-2005') OB_BAL,
    SUM(STKTRAN.QTYIN) QTYIN,
    SUM(STKTRAN.QTYOUT) OUT,
    END_BAL(PID,31-OCT-2005) END_BAL
    FROM PRODUCTS, STKTRAN
    WHERE PRODUCTS.PID = STKTRAN.PID
    AND STKTRAN.SDATE BETWEEN '01-OCT-2005' AND '31-OCT-2005'
    GROUP BY
    TO_CHAR(STKTRAN.SDATE,'MON,YY'), PRODUCTS.PNAME;
    MON PNAME OB QTYIN OUT BAL
    OCT,05 GX-150 1000 18655 12300 7355
    OCT,05 GX-220 0 20500 18245 2255
    opening balance is the qty_in_stock + qty_purchased - qty_sold before 01-oct-05.
    ending balance is the qty_in_stock + qty_purchased - qty_sold before 01-nov-05.
    the problem is i want to get result between two dates. suppose between
    01-jan-05 and 31-dec-05 group by month n product.
    "one month ending balance should be the opening balance of other. " ???
    means it will look like ....
    MON PNAME OB QTYIN OUT BAL
    OCT,05 GX-150 1000 18655 12300 7355
    OCT,05 GX-220 0 20500 18245 2255
    NOV,05 GX-150 7355 1000 5355 3355
    NOV,05 GX-220 2255 1000 1255 2255
    please guide me ......thanks

    If you have 8i enterprise edition, then analytic functions are supported and you could use this solution:
    SQL> create table products
      2  as
      3  select 1 pid, 'GX-150' pname from dual union all
      4  select 2, 'GX-220' from dual
      5  /
    Tabel is aangemaakt.
    SQL> create table stktran
      2  as
      3  select date '2005-01-20' sdate, 1 pid, 1000 qtyin, 0 qtyout from dual union all
      4  select date '2005-10-10', 1, 18655, 12300 from dual union all
      5  select date '2005-10-10', 2, 10500, 10000 from dual union all
      6  select date '2005-10-20', 2, 10000, 8245 from dual union all
      7  select date '2005-11-11', 1, 1000, 5355 from dual union all
      8  select date '2005-11-11', 2, 1000, 1255 from dual
      9  /
    Tabel is aangemaakt.
    SQL> var P_STARTDATE varchar2(10)
    SQL> var P_ENDDATE varchar2(10)
    SQL> exec :P_STARTDATE := '01-01-2005'
    PL/SQL-procedure is geslaagd.
    SQL> exec :P_ENDDATE := '31-12-2005'
    PL/SQL-procedure is geslaagd.
    SQL> select pname
      2       , to_char(m,'MON,yy') mon
      3       , lag(eb,1,0) over (partition by pname order by m) ob
      4       , qtyin
      5       , qtyout
      6       , eb
      7    from ( select pname
      8                , mon m
      9                , qtyin
    10                , qtyout
    11                ,   sum(nvl(qtyin,0)) over (partition by pname order by mon)
    12                  - sum(nvl(qtyout,0)) over (partition by pname order by mon) eb
    13             from ( select pname
    14                         , trunc(sdate,'mm') mon
    15                         , sum(qtyin) qtyin
    16                         , sum(qtyout) qtyout
    17                      from ( select p.pname
    18                                  , s.sdate
    19                                  , s.qtyin
    20                                  , s.qtyout
    21                               from products p
    22                                  , stktran s
    23                              where s.pid = p.pid
    24                                and s.sdate between to_date(:P_STARTDATE,'dd-mm-yyyy') and to_date(:P_ENDDATE,'dd-mm-yyyy')
    25                             union all
    26                             select pname
    27                                  , mon
    28                                  , null
    29                                  , null
    30                               from ( select add_months(trunc(to_date(:P_STARTDATE,'dd-mm-yyyy'),'mm'),level-1) mon
    31                                        from dual
    32                                     connect by level <=
    33                                             months_between
    34                                             ( trunc(to_date(:P_ENDDATE,'dd-mm-yyyy'))
    35                                             , trunc(to_date(:P_STARTDATE,'dd-mm-yyyy'))
    36                                             ) + 1
    37                                    )
    38                                  , ( select pid
    39                                           , pname
    40                                        from products
    41                                    )
    42                           )
    43                     group by pname
    44                         , trunc(sdate,'mm')
    45                  )
    46         )
    47   order by m
    48       , pname
    49  /
    PNAME  MON            OB      QTYIN     QTYOUT         EB
    GX-150 JAN,05          0       1000          0       1000
    GX-220 JAN,05          0                                0
    GX-150 FEB,05       1000                             1000
    GX-220 FEB,05          0                                0
    GX-150 MRT,05       1000                             1000
    GX-220 MRT,05          0                                0
    GX-150 APR,05       1000                             1000
    GX-220 APR,05          0                                0
    GX-150 MEI,05       1000                             1000
    GX-220 MEI,05          0                                0
    GX-150 JUN,05       1000                             1000
    GX-220 JUN,05          0                                0
    GX-150 JUL,05       1000                             1000
    GX-220 JUL,05          0                                0
    GX-150 AUG,05       1000                             1000
    GX-220 AUG,05          0                                0
    GX-150 SEP,05       1000                             1000
    GX-220 SEP,05          0                                0
    GX-150 OKT,05       1000      18655      12300       7355
    GX-220 OKT,05          0      20500      18245       2255
    GX-150 NOV,05       7355       1000       5355       3000
    GX-220 NOV,05       2255       1000       1255       2000
    GX-150 DEC,05       3000                             3000
    GX-220 DEC,05       2000                             2000
    24 rijen zijn geselecteerd.Regards,
    Rob.

  • SQL syntax Problem

    let's say i want to get exactly the total service for an employee (how many years, how many months & how many days):
    the Appointment date is : 11/17/1992
    the Termination date is : 03/06/2001
    by using months_between it will be like this:
    select month_between(to_date('03/06/2001','MM/DD/YYYY'),to_date('11/17/1992','MM/DD/YYYY')) from dual;
    it will give exactly : 99.6451613 ,then
    we will divide it by 12 to get the years ,then we can truncate it to get the hole figure of the years, it will give exactly 8 years , my problem starts from here : how to get the months and the days?!!!!
    null

    Try this:
    select trunc(m/12) "Years", trunc(m-trunc(m/12)*12) "Months", (m-trunc(m))*31 "Days" from (select months_between(to_date('03/06/2001','MM/DD/YYYY'),to_date('11/17/1992','MM/DD/YYYY')) as m from dual where rownum=1)
    I did not check it (too many days to count :), but the results are reasonable.

  • Months_between

    I have been having some troubles with the months_between function.
    It seems to be returning 1 less month than what I'm expecting.
    Have anyone been experiencing this problem?
    I have included a code snippet and the dates I'm comparing.
    UPDATE CLTV_POST
    SET
    ACCOUNT = RC1.CUSTOMER_ACCOUNT,
    NO = RC1.MSDN,
    SQTR_NUMBER = RC1.SQTR_NUM,
    LOA = NVL(TRUNC(MONTHS_BETWEEN(SYSDATE,RC1.SUBSCRIPTION_DATE)),LOA)
    WHERE MID = RC1.MID;
    I'M comparing the SYSDATE with the SUBSCRIPTION_DATE = 04JUL2001
    Your help is greatly appreciated.
    Karim.

    Gillian,
    But wait, do you want the person's age as of the day in question, or not? I'm confused.
    If my birthday is April 15th, 1968, then on April 14, 2002, I'm still 33 years old. I don't turn 34 until April 15th, 2002:SQL> SELECT
      2  RPAD(TO_CHAR(days.day_to_check_age,'fmMM/DD/YYYY'),16) "Day To Check Age"
      3  ,'4/15/1968' "Birthday"
      4  ,TRUNC(MONTHS_BETWEEN(days.day_to_check_age
      5         ,              TO_DATE('19680415','YYYYMMDD')) / 12
      6  ,     0) age
      7  FROM
      8  (SELECT TO_DATE('20020414','YYYYMMDD') + ROWNUM - 1   day_to_check_age
      9   FROM   all_objects
    10   WHERE  ROWNUM <= 3) days
    11   /
    Day To Check Age Birthday         AGE
    4/14/2002        4/15/1968         33
    4/15/2002        4/15/1968         34
    4/16/2002        4/15/1968         34
    SQL> When is the last day you expect your function to report this person as being 33?
    T.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

Maybe you are looking for

  • Connect iBook to LCD TV?

    Hi, Wonder if anyone can help...I am trying to connect my iBook G3 to my Phillips LCD TV. My problem is the cable. I am using the supplied DVI to VGA connector, however my TV has the same VGA connection on it. In other words two females and it theref

  • Distiller in Adobe Acrobat Standard 8.0?

    We are currently using Adobe Acrobat Standard 6.0 to convert PostScript files to PDF. Is this functionality still included in the Adobe Acrobat Standard 8.0 package, or has the Distiller component been removed/upgraded to the Distiller Server compone

  • Flash CS3 Form Application doesn't support FlashVars?

    Anyone try load FlashVars in Form Application? It doesn't work. Why? In HTML object tag i add: <param name="FlashVars" value="varvalue=myValue" /> <embed src="flash/student.swf" FlashVars="varvalue=myValue" ... And on frame on first form (named: appl

  • Web dynpro Java on Blackberry

    Hi all, I'm developing a WD app on blackberry but I got stuck in binding data from a context node to my table. My problem is the table rows do not display correct data on each row. I do create different context data elements and add to the correct no

  • Sql query/subquery large database

    Hi, I'm trying to select users from a log which also has an entry in the log in the month before.. I manage to get results, but they are pretty slow, and I would really like them to get faster.. select count(*) from(select user_id from app_user_log w