0

Basically i am new to the fragment, i have to connect my database with my fragment and for that i have to initialize my firebase context but it gives error under (this). Any alternative for that?

CODE

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {
            Firebase.setAndroidContext(this); //error
        }
}
Aashir Javed
  • 101
  • 1
  • 15
  • 1
    Possible duplicate of [Using context in a fragment](http://stackoverflow.com/questions/8215308/using-context-in-a-fragment) – Mike M. May 07 '16 at 11:07

1 Answers1

0

Fragment does not have a Context by itself. You need to call

Firebase.setAndroidContext(this.getActivity());

Because Activity does have context. You can do so in onAttach() method, because the Fragment that's what's called when Fragment is actually attached to an Activity. Alternatively, you can leave it in onCreate() since it gets called after onAttach(). Check the official documentation here. Might be useful for you to learn the order in which Fragment's methods are being called.

Vucko
  • 7,371
  • 2
  • 27
  • 45
  • Thanks it works, if i want to do casting like use **findViewById** to save my text what should i do? i am currently using getView() but it's not working. – Aashir Javed May 07 '16 at 11:13
  • Well this is actually another matter. Please accept the answer if it fixed your problem. I can write you how you can use findViewById here but it will be ugly and in one line cause formatting in comments is different. – Vucko May 07 '16 at 11:14
  • You need to do it in `onCreateView` method. Something like this `View view = inflater.inflate(R.layout.your_fragment_id, container, false); myListView = (ListView) view.findViewById(R.id.myListView);` – Vucko May 07 '16 at 11:15
  • Pay attention that this needs to be done in `onCreateView`. The easiest way to override methods in Android Studio is to click CTRL+O and start typing the name of the method and it'll find it for ya. – Vucko May 07 '16 at 11:17