0

I'm using a "createUserWithEmailAndPassword" method from Firebase and I need to send a context (activity) to it.

But this is inside a Static method (have to be this way because I'm using Fragments.). So, I collect all the data inside the Fragment and send to "registerUser" method in the MainActivity.

So, because this methos (registerUser) is a Static Mode, the MainActivity is not being referenced by the "createUser..." from Firebase.

I've tried to use "This" keyword. I've tried to use "new" keyword, like:

MainActivity main = new MainActivity();

But both does not work and using the "new" keyword, the code is not even compiled.

Someone to help me?

The image below shows the code inside the MainActivity. enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
rioleal
  • 33
  • 1
  • 9
  • i don't think the `static` method keyword is needed here since your `MainActivity` will always be instantiated on startup. – user3170251 Jan 10 '20 at 15:47

3 Answers3

1

Static methods, by definition, don't run in the context of an enclosing class instance. There is no this instance to reference. If you need to reference another class instance from a static method, you will need to pass it as a parameter to the function.

public static String cadUsario(MainActivity activity, Usario pUsario) {
    // now use activity where needed
}

Consider also not using a static method at all. That might not be appropriate here.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

You can pass context object of your Activity to another Activity with constructor parameters. Check this answer Link

Your problem; If you want to use context object in same class with static context, you can create a global variable like this;

     public class MainActivity extends AppCompatActivity {

        private static Context context;

        @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                context = this;

            }

        public static String cadUsusario(Usuario pUsuario){

        // use "context" variable by itself or create new variable. It's up to you.
        Context myContext = context;
        // your codes below

        }
}
TeachMeJava
  • 640
  • 1
  • 13
  • 35
1

I'm really so glad to your answers and they are very enlightening to me.

A brazilian friend help me in this task: enter image description here

He taught me to write this code inside the Fragment, using getActivity in onAttach from Fragment and declare a private Context context. So, I could use getActivity with Firebase.

rioleal
  • 33
  • 1
  • 9