Android Code Snippet get the current activity (from a code module)

Discussion in 'Code Snippets' started by Dave O, Jul 5, 2016.

  1. Dave O

    Dave O Active Member Licensed User

    If you're in a code module, you don't have the Activity object handy to reference.

    Here's a simple sub (courtesy of Erel) that fetches the current B4A activity:

    Code:
    Sub getCurrentActivity As Activity
       
    Dim r As Reflector
       r.Target = r.GetActivityBA
       
    Return r.GetField("vg")   
    End Sub
     
    Star-Dust and lemonisdead like this.
  2. lemonisdead

    lemonisdead Well-Known Member Licensed User

    Thanks. What does "vg" stand for ? Thanks
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    This is an internal field that points to the Activity view.
     
    Dave O and lemonisdead like this.
  4. swabygw

    swabygw Active Member Licensed User

    I know this is an old thread, but I could use this. However, when I run it in my Activity, I get the following: "(BALayout): Layout not available". This is my execution (within Activity_Create section):

    Code:
    Log("act:" & getCurrentActivity)
     
  5. Erel

    Erel Administrator Staff Member Licensed User

    You can ignore this message.
     
  6. peacemaker

    peacemaker Well-Known Member Licensed User

    So, each Activity must contain this sub ? No way to detect from the single sub the current active Activity ?
     
  7. Star-Dust

    Star-Dust Expert Licensed User

    Great, I needed it right
     
    ofc500k likes this.
  8. Alpandino

    Alpandino Member Licensed User

    I tried to use this code in a service, but I receive this error:

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference

    I tried in both cases: app in foreground and app in background.
    Maybe I can't use this code in a service?
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice