I have setup a Observable/Subscriber with RxJava. The Observable is created in MainActivity. The Subscriber is a android.support.v4.app.Fragment
called MyFragment. The Observable gets data from RESTful service and stores the data in a SQLite db on the device. This works. When its work is done, which takes 4 or 5 seconds such that MyFragment has already processed onCreate()
, onCreateView()
etc., the subscriber, MyFragment, is notified via its implemented onNext()
method (this works) and is then reads data from the SQLite db (this also works) and is the supposed to populate a view (this does not work).
The problem is that my class member mActivity is null in the method loadDataFromSQLite()
. The lesson I think I am learning is that nothing with a Fragment
can be done outside of methods in the Fragment class (from onAttach()
to onDestroy()
)
That being the case, how do I do this?
See below for code snippets:
MyFragment.java
public class MyFragment extends Fragment implements Observer<String> {
private Activity mActivity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
...
@Override
public void onNext(String string) {
loadDataFromSQLite();
}
public void loadDataFromSQLite() {
<get data from SQLite>
// now want to populate view
// mActivity is null
mTableLayout = (TableLayout) mActivity.findViewById(R.id.fragment_table_layout);
}
}
fragment_table_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/table_wrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="none"
tools:ignore="UselessParent">
<TableLayout
android:id="@+id/fragment_table_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- fill in data in MyFragment.java -->
</TableLayout>
</ScrollView>
</RelativeLayout>
Edit:
I should add the I also tried calling getActivity()
in place of mActivity
, but it returns null