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

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:

B4X:
Sub getCurrentActivity As Activity
   Dim r As Reflector
   r.Target = r.GetActivityBA
   Return r.GetField("vg")   
End Sub
 

lemonisdead

Well-Known Member
Licensed User
Longtime User
Thanks. What does "vg" stand for ? Thanks
 

swabygw

Active Member
Licensed User
Longtime 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):

B4X:
    Log("act:" & getCurrentActivity)
 

peacemaker

Expert
Licensed User
Longtime User
So, each Activity must contain this sub ? No way to detect from the single sub the current active Activity ?
 

Star-Dust

Expert
Licensed User
Longtime User
Great, I needed it right
 

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?
 
Top