Problem in BAPI_HU_CREATE

Dear All,
Im using BAPI_HU_CREATE for creating the handling unit, but when i run the program, i m getting a message HU cannot be created and the HU is not getting created,pls find the below coding im using in my program and tell me what could be wrong in this.
DATA: st_huhdrpr TYPE bapihuhdrproposal,
        st_huhdr   TYPE  bapihuheader,
        st_huhdr_pack   TYPE  bapihuheader,
        it_pr      LIKE TABLE OF bapihuitmproposal WITH HEADER LINE,
        it_huitem  LIKE TABLE OF bapihuitem,
        it_huitem_pack TYPE bapihuitem,
        it_hunumber LIKE TABLE OF bapihunumber WITH HEADER LINE.
  REFRESH it_ret.
  st_huhdrpr-hu_status_init  = 'C'.
  st_huhdrpr-pack_mat        = v_pac_matnr.
  SELECT SINGLE * FROM lips WHERE vbeln EQ likp-vbeln
                            AND   lfimg GT 0.
  st_huhdrpr-plant           = lips-werks.
  st_huhdrpr-stge_loc        = lips-lgort.
  LOOP AT it_scan ASSIGNING <fs_scan> .
    it_pr-hu_item_type = '1'.
    it_pr-material     = <fs_scan>-matnr.
    it_pr-material_partner = <fs_scan>-j_3akordx.
    it_pr-batch        = <fs_scan>-charg.
    it_pr-pack_qty     = <fs_scan>-count.
    it_pr-base_unit_qty = 'ST'.
    it_pr-plant        = st_huhdrpr-plant.
    it_pr-stge_loc     = st_huhdrpr-stge_loc.
    it_pr-number_pack_mat = <fs_scan>-count.
    APPEND it_pr.
  ENDLOOP.
*Call to BAPI
  CALL FUNCTION 'BAPI_HU_CREATE'
       EXPORTING
            headerproposal = st_huhdrpr
       IMPORTING
            huheader       = st_huhdr
            hukey          = v_hukey
       TABLES
            itemsproposal  = it_pr
            return         = it_ret
            huitem         = it_huitem.
  CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.
  IF NOT v_hukey IS INITIAL.
    APPEND v_hukey TO it_hukey.
    LOOP AT it_scan ASSIGNING <fs_scan> .
      MOVE-CORRESPONDING <fs_scan> TO it_hunit.
      MOVE v_hukey TO it_hunit-hukey.
      APPEND it_hunit.
      CLEAR it_hunit.
    ENDLOOP.
    PERFORM packing_print.
  ELSE.
    MESSAGE e000(38) WITH
    'HU Creation and Packing failed Click on LOG to see errors'.
  ENDIF.
  REFRESH : it_pr,it_huitem.
ENDFORM.                    " create_handling_unit

Please have a look at the below mentioned code.
LOOP AT gt_final1 INTO gs_final1.
item proposal
gs_itemsproposal-hu_item_type = c_1. " material item
gs_itemsproposal-pack_qty = gs_final1-erfmg. " quantity
gs_itemsproposal-base_unit_qty = 'EA'. " unit of measure
IF NOT gs_final1-matnr IS INITIAL.
gs_itemsproposal-material = gs_final1-matnr. " zlpm material
ELSE.
gs_itemsproposal-material = gs_final1-matnr1. " material(component)
ENDIF.
gs_itemsproposal-plant = gs_final1-werks. " plant
gs_itemsproposal-stge_loc = gs_final1-lgort. " storage location
gs_itemsproposal-batch = gs_final1-charg. " batch
passing values into variables before AT NEW
gv_matnr = gs_final1-matnr.
AT NEW sernr.
populate no of sernr
gs_itemsproposal-no_of_serial_numbers = c_1.
read table to check if the 1st matnr of new
sernr is of type ZLPM or not
also populate pack_mat and pack inst
READ TABLE gt_mara INTO gs_mara WITH KEY matnr = gv_matnr
mtart = c_zlpm BINARY SEARCH.
IF sy-subrc = c_0.
populate pack_mat
IF gs_mara-magrv+0(2) = c_im.
gv_pack_mat = text-032. " IMPLANT_SET
ELSEIF gs_mara-magrv+0(2) = c_in.
gv_pack_mat = text-035. " INSTRUMENT_KIT
ENDIF.
pack inst
lv_pobjid = gv_matnr.
CALL FUNCTION 'VHUPODB_PACKOBJ_CONV_ID2GUID'
EXPORTING
pobjid_imp = lv_pobjid
packtyp_imp = c_p
IMPORTING
packnr_exp = gv_packg_instruct
EXCEPTIONS
prog_error = 1
pobjid_not_found = 2
OTHERS = 3.
IF sy-subrc 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ELSE.
populate msg if 1st material of new sernr is
not of type ZLPM
gv_tabix = gv_tabix + c_1.
gs_error1-sno = gv_tabix.
gs_error1-matnr = gv_matnr.
gs_error1-sernr = gs_final1-sernr.
gs_error1-msg = text-037. " First material of this serial number is not of type ZLPM
APPEND gs_error1 TO gt_error1.
DELETE gt_final1 WHERE sernr = gs_final1-sernr.
CONTINUE.
ENDIF.
ENDAT.
APPEND gs_itemsproposal TO gt_itemsproposal.
CLEAR gs_itemsproposal.
gv_werks = gs_final1-werks.
gv_lgort = gs_final1-lgort.
bapi will be called only on the change of sernr
AT END OF sernr.
used for setting the local pack status
calculate no of items in itemsproposal table
DESCRIBE TABLE gt_itemsproposal LINES lv_no_lines.
read total materials available in this pack inst
here lv_pobjid contains the name of ZLPM material
READ TABLE gt_packkp INTO gs_packkp WITH KEY matnr = lv_pobjid.
IF sy-subrc = c_0.
if all material in pack inst are included in HU
IF gs_packkp-number = lv_no_lines.
gs_bapihuhdrproposal-l_packg_status_hu = c_3. " Local packing status of HU
if all material in pack inst are not included in HU
ELSEIF gs_packkp-number lv_no_lines.
gs_bapihuhdrproposal-l_packg_status_hu = c_2. " Local packing status of HU
ENDIF.
ENDIF.
header proposal
gv_sernr = gs_final1-sernr.
gs_bapihuhdrproposal-pack_mat = gv_pack_mat. " packaging material
gs_bapihuhdrproposal-plant = gv_werks. " plant
gs_bapihuhdrproposal-stge_loc = gv_lgort. " storage location
gs_bapihuhdrproposal-packg_instruct = gv_packg_instruct. " packaging instruction
serial number
gs_itemsserialno-row_index = c_1. " row index
gs_itemsserialno-serialno = gs_final1-sernr. " serial number
APPEND gs_itemsserialno TO gt_itemsserialno.
CLEAR gs_itemsserialno.
bapi for hu creation
CALL FUNCTION 'BAPI_HU_CREATE'
EXPORTING
headerproposal = gs_bapihuhdrproposal
IMPORTING
huheader = gs_huheader
hukey = gv_hukey
TABLES
itemsproposal = gt_itemsproposal
itemsserialno = gt_itemsserialno
return = gt_return
huitem = gt_huitem.
gv_tabix = gv_tabix + c_1.
gs_summary1-sno = gv_tabix.
here lv_pobjid contains the name of ZLPM material
gs_summary1-matnr = lv_pobjid.
gs_summary1-sernr = gs_final1-sernr.
SHIFT gs_summary1-sno LEFT DELETING LEADING space.
IF gt_return IS INITIAL. " HU created successfully
transaction commit
CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'
EXPORTING
wait = c_x.
Please give points if useful.

Similar Messages

  • Problem using BAPI_HU_CREATE ?

    Hi All,
    I am generating HUs using BAPI_HU_CREATE it is creating HUs fine, values are updated in VEKP and VEPO Table. In VEKP(Header ) Table two fields are there VPOBJ and VPOBJKEY. By deafult after using this BAPI VPOBj - 12(Non-Assigned Handling Unit) and VPOBJKEY is some value (0000001724). After this i am using WS_DELIVERY_UPDATE_1 but delivery is not updating.
    So after BAPI_HU_CREATE i used another bapi BAPI_HU_CHANGE_HEADER and i change values of VPOBJ-03 and VPOBJKEY(delivery no). Now WS_DELIVERY_UPDATE_1 is working and delivery is updating successfully.
    Now here the problem is in VEPO four records are there with old VPOBJ and VPOBJKEY and new values.I dont want to create first two records, how can i rectify this... Please help me
    Atleast tell me anyone how to delete first 2 records from VEPO Table. Is there any FM is there to update VEPO Table.
    Thanks,
    Venkat.
    Edited by: venkat1011 on May 9, 2011 2:46 PM

    Hi Venkat,
    Are you sure you are clearing the variables appropriately, i mean before you start building the data for "BAPI_HU_CREATE" are you doing a clear/refresh on the corresponding variables?
    Regards,
    Chen

  • Problem with BAPI_HU_CREATE

    Hi,
    I would create handling units. (Transaction HUP30).
    During the creation process, how recover the packaging material starting from base material, and pass it to BAPI_HU_CREATE?
    The VHUSUBSC_PROCESS_USERINPUT function module, recover the packaging material, but work only in standard transaction.
    Thanks and sorry for my bad english.
    p.s: PROCESS_HU_INBOUND_DLVRY and BAPI_INB_DELIVERY_CHANGE don't work!
    Merchiorre
    null

    Hi,
           use the following BAPI's    PROCESS_HU_INBOUND_DLVRY
    BAPI_INB_DELIVERY_CHANGE.
    Regards

  • HU Create Problem

    Hi Experts,
    I am trying to create an uassigned Hu thru BAPI_HU_CREATE by providing the Packaging Material No in the HEADERPROPOSAL-PACK_MAT field.Now post executing the BAPI 'm able to get the HU no but the entry is not reflected in VEKP  and VEPO tables. I am also performaing and explicit COMMIT WORK thru BAPI_TRANSACTION_COMMIT.
    Post HU creation I'm also required to PACK it with a delivery line item.
    Please suggests if i am missing something.
    Thanx,
    Akhil

    Hi, Sharad.
    I was facing a similar problem.
    In my program i use BAPI_HU_PACK and then HU_CREATE_GOODS_MOVEMENT.
    As the code above gives a dump then i created a testing program where i use the BAPI HU_CREATE_GOODS_MOVEMENT isolated. It works perfectly.
    So the problem must be some variable that is not cleared
    To solve my problem i added the following FM's before HU_CREATE_GOODS_MOVEMENT:
    CALL FUNCTION 'HU_PACKING_REFRESH'.
    CALL FUNCTION 'SERIAL_INTTAB_REFRESH'.
    CALL FUNCTION 'L_SAPLL03A_INIT_INT'.
    Regards,
    Pedro

  • Problem in deleting Handling unit

    Hi,
      I have created a program in which I have to create a HU and pack a material into it. For this I have used BAPI BAPI_HU_CREATE. Then I am packing this newly created HU to another HU using BAPI BAPI_HU_PACK. In between these 2 BAPI calls I made goods movement using tcode VLMOVE. This I have done using BDC. This process works fine.
       After the creation of HU and Packing if I press a button to delete the HU, it should delete the selected HU. For the deletion of HU I have used BAPI_HU_DELETE. But it is not deleting. But when I start my program again and try to delete it is working.
      Deletion is not working only when I try it after creation of HU.(there is a button for creation too).
    For eg. If I have created and packed successfully a HU say HU1 and I try to delete it , it is not working.
    If I start the program and try, it deletes HU1.
    Could anyone please tell me the reason for this.
    Order of my BAPI call.
    BAPI_HU_CREATE
    BDC for VLMOVE
    BAPI_HU_PACK
    finally when pressing delete button
    BAPI_HU_DELETE
    Do I have to call some FM or BAPI to clear the memory or something like that. Please help me to solve this issue.
    Thanks & Regards,
    Jisha.

    Hi Preetham,
    Thanks for your fast response.
    Yes. There was an error message. The error message was the  u2018The handling unit contains items that cannot be deletedu2019. But if I start the program again it deletes correctly.
    The problem occurs only when I try soon after creating and packing the HU.
    After every BAPI call I am using BAPI_TRANSACTION_COMMIT with wait = u2018Xu2019.
    Thanks & Regards,
    Jisha.

  • Problem in 'HU_CREATE_GOODS_MOVEMENT'/ HU02

    Hi All,
    We are trying to create a HU and move the stock to a destination storage location.This provision exists in transaction HU02.
    But the 'BAPI_HU_CREATE' has no field where i can enter the destination storage location.So after creating the HU's with the above bapi we are using FM 'HU_CREATE_GOODS_MOVEMENT' to do the movement.
    My problem is that the above mentioned FM is not working properly.
    Its giving me errors/dumps based on the HU details iam entered into it.
    Can somebody give me a solution for the same.
    It would be great if i get some sample code for the above mentioned FM .
    Kindly help, its really urgent.
    Thank You

    Hi, Sharad.
    I was facing a similar problem.
    In my program i use BAPI_HU_PACK and then HU_CREATE_GOODS_MOVEMENT.
    As the code above gives a dump then i created a testing program where i use the BAPI HU_CREATE_GOODS_MOVEMENT isolated. It works perfectly.
    So the problem must be some variable that is not cleared
    To solve my problem i added the following FM's before HU_CREATE_GOODS_MOVEMENT:
    CALL FUNCTION 'HU_PACKING_REFRESH'.
    CALL FUNCTION 'SERIAL_INTTAB_REFRESH'.
    CALL FUNCTION 'L_SAPLL03A_INIT_INT'.
    Regards,
    Pedro

  • Error in BAPI_HU_CREATE

    Hi,
    When I execute BAPI_HU_CREATE, I get following error :
    "00517848450E does not have packaging material type and is therefore not a pack.mat."
    my code is below :
           call function 'BBP_INB_DELIVERY_CREATE'
              exporting
                is_inb_delivery_header = is_inb_delivery_header
              importing
                ef_delivery            = ef_delivery
              tables
                it_inb_delivery_detail = gt_inb_delivery_detail
                return                 = gt_return.
            call function 'BAPI_TRANSACTION_COMMIT'.
            if ef_delivery is not initial.
              clear : gs_headerproposal,
                      gs_huheader,
                      gs_hukey.
              refresh : gt_itemsproposal,
                        gt_itemsserialno,
                        gt_return1,
                        gt_huitem.
              gs_itemsproposal-HU_ITEM_TYPE       = '1'.               " material item
              gs_itemsproposal-base_unit_qty      = 'EA'.              " unit of measure
              gs_itemsproposal-material           = gs_ekpo-matnr.   " zlpm material
              gs_itemsproposal-plant              = gs_ekpo-werks.   " plant
              gs_itemsproposal-stge_loc           = gs_ekpo-lgort.   " storage location
              read table poitem index 1.
              if sy-subrc = 0.
                gs_itemsproposal-batch              = poitem-BATCH.   " batch
                gs_itemsproposal-pack_qty           = poitem-quantity.   " quantity
              endif.
              gs_itemsproposal-no_of_serial_numbers = '1'.
              append gs_itemsproposal to gt_itemsproposal.
              gs_headerproposal-pack_mat          = gs_ekpo-matnr.     " packaging material
              gs_headerproposal-plant             = gs_ekpo-werks.     " plant
              gs_headerproposal-stge_loc          = gs_ekpo-lgort.     " storage location
    *          gs_headerproposal-packg_instruct    = gv_packg_instruct. " packaging instruction
              gs_itemsserialno-row_index          = '1'.               " row index
              gs_itemsserialno-serialno           = '1'.   " serial number
              append gs_itemsserialno to gt_itemsserialno.
              call function 'BAPI_HU_CREATE'
                exporting
                  headerproposal = gs_headerproposal
                importing
                  huheader       = gs_huheader
                  hukey          = gs_hukey
                tables
                  itemsproposal  = gt_itemsproposal
                  itemsserialno  = gt_itemsserialno
                  return         = gt_return1
                  huitem         = gt_huitem.
              if sy-subrc = 0.
                call function 'BAPI_TRANSACTION_COMMIT'.
              endif.
            endif.
    Pls help ..
    Regards,

    Hi Santosh,
    The problem could be with the material used for crating the delivery and hence packing.
    Try to create manually the delivery and do the packing for the same material and see if you are getting that error.
    If Yes, then probably you have to choose another material for testing your logic.
    Take help of your functional consultant as well.
    Br..
    Dwaraka

  • How to pass Delivery nuber in BAPI_HU_CREATE and BAPI_HU_PACK

    Hi experts,
    I used BAPI_HU_CREATE to create a Handling unit and using BAPI_HU_PACK i'm sucessfully able to pack the materials. My problem is starts with the delivery number, how to pass the delivery number to the BAPI's, when i go and see in vekp & vepo tables the delivery field is blank . So that i cant able to correlate this packing has been done for this delivery.
    Kindly help me out..
    With regards,
    James...
    Valuable answers will be rewarded...

    Hi,
    BAPI for HU is meant to deal with free-HUs, that is HUs that are not
    assigned to any document. But once the HUs have been created/changed,
    they can be processed with standard transaction codes, and you can also
    assign it to any document.
    You could also create HUs for deliveries with IDOC or function module
    WS_DELIVERY_UPDATE. Please check note 581282 for more information about this.
    Regards,
    Ely

  • Packing materials in delivery problem

    Hi ,
      I m creating handling units with BAPI_HU_CREATE and then packing them with BAPI_HU_PACK. But the problem is the items that i pack dont go away from my lower table in delivery, they remain available for packing.
    My objective is to programmatically do the following
    1. Create handling units
    2. Pack items in the delivery in the handling units
    Will give points for the right answer, especially code. Thanks for reading

    Hi,
    To pack items in handling unit linked to a delivery, you can use FM WS_DELIVERY_UPDATE_2.
    Here is an example of the call of FM:
    w_vbkok-vbeln_vl = p_vbeln. "delivery number
    w_verko-exidv = wa_vekp_pal-exidv. "HU in which you pack
    APPEND w_verko TO i_verko.
    CLEAR w_verpo.
    w_verpo-exidv_ob = wa_vekp_pal-exidv.
    w_verpo-EXIDV = wa_vekp_col-exidv.
    w_verpo-velin = '3'. " 3 to pack a HU in another one
    " 1 to pack a material in a HU
    w_verpo-vbeln = p_vbeln.
    APPEND w_verpo TO i_verpo.
    CLEAR i_repack.
    w_repack-desthu = wa_vekp_pal-exidv. "HU in which you pack
    w_repack-sourcehu = wa_vekp_col-exidv. "HU to be packed
    w_repack-packhu = 'X'.
    APPEND w_repack TO i_repack.
    CALL FUNCTION 'WS_DELIVERY_UPDATE_2'
    EXPORTING
    vbkok_wa = w_vbkok "delivery number
    delivery = p_vbeln
    TABLES
    prot = i_prot
    verko_tab = i_verko
    verpo_tab = i_verpo
    it_repack = i_repack
    EXCEPTIONS
    error_message = 1
    OTHERS = 2.
    COMMIT WORK AND WAIT.

  • Handling unit created with BAPI_HU_CREATE   doesnt show up in Delivery

    Hi
      I m successfully creating a handling unit with the following code in a delivery user exit on Save. I can see the handling unit in the VEKP table. But if i open the delivery i cant see it. The VPOBJKEY has some weird value like 3342 instead of the delivery number. Please let me know the problem, possibly with code. Will give points. Thanks for reading.
    l_header-pack_mat     = '800'.
      l_header-hu_exid_type = 'E'.
      l_header-ext_id_hu_2  = 'TEST'.
      l_header-content      = 'JUNK'.
      l_header-VOLUMEUNIT = 'CCM'.
      l_header-hu_exid = '1234'.
      CALL FUNCTION 'BAPI_HU_CREATE'
        EXPORTING
          headerproposal       = l_header
       IMPORTING
         huheader             =  l_huhead
         hukey                =  l_hukey
        TABLES
        ITEMSPROPOSAL        =    IT_PROP
      ITEMSSERIALNO        =
          return               = l_it_ret
        huitem               = it_item

    Hi,
    I am creating a HU with following params, they work fine for me,
    maybe you could try them out.
    l_header-pack_mat = '<INT'. 
    l_header-hu_exid  = '$1'.
    l_header-hu_exid_type = 'C'.
    l_header-plant = your plant.
    l_header-stge_loc = your storage location.
    Regards,
    Dirk.

  • 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.

Maybe you are looking for

  • Excel cells colors by labiew 2009

    Hi, I have an application. Where in i have to change the colors of Cells in Excel as per the result after doing some manipulations on my data. Exampe : if true then color to green and if False then color to Red. I use Labview2009, Microsoft office 20

  • Photoshop CS6 won´t recognize ACR after installing ACR 8.4 beta.

    Hi all, just today Adobe has relaeased the new ACR 8.4 beta. As usual I downloaded it, installed it to my Photoshop CS6 (running on a 2010 iMac/ OS is 10.6.8), and to my surprise PS no longer was able to find ACR at all. In other words: I could no lo

  • Entourage 2008 Sync

    I have just downloaded 4.1.25 and I am using Microsoft Entourage 12.1.2. and I get this error when trying to synchronize [05:14:22.078] Could not lcoate the Microsoft Entourage Office Synchronization Tool. [05:14:26.718] Could not lcoate the Microsof

  • Can't update to the new calendar

    I have now spent 4 hours today trying to get my iCal working - and I've been a Mac user since 1990. I do have a calendar on Mobile Me -- calendar/old -whatever that is.. I have tried to update to the new calendar 4 times -- and I get an error message

  • No available resource. Wait-time expired.

    Dear All I am using sun ONE applications server. I am struggling with No available resource. Wait-time expired problem. MY Pool configurations are steady:20,max:100,inc:2. My code is very straight forward. Getting the connection, using the connection