Jaythaking
Jaythaking

Reputation: 2102

SQLite database using Fragment in Android

I'm making an app which have multiple fragment. One of those fragment shows the Data from a Database. The fragment are called from the MainActivity and redirected to the external class "fragment_database".

But, whenever I try to add function in this external class "Fragment_Database.java", that generate a scope error or a missing function error. All the function require that the class extend the Activity class but mine extends the Fragment class instead...

Here is my external fragment_database class:

public class Fragment_Database extends Fragment{
public Fragment_Database() {

    // HERE??

}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_database, container, false);

    // HERE??

    return v;
}

Am I suppose to put the database function in this class or in the MainActivity? I'm a little lost on the structural aspect of my project...

Thanks

Upvotes: 1

Views: 2486

Answers (1)

Szymon
Szymon

Reputation: 43023

If you need to add anything that requires an Activity, you can obtain a reference to it by using getActivity() method from a fragment.

It's best to put it into onActivityCreated() method as it's

Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle).

Upvotes: 1

Related Questions