Setting view in constructor Android with fragment

81 views Asked by At

I'm getting a java java.lang.NullPointerException error when I'm trying to set a view in a class while using the constructor. I can't see what I'm doing wrong here.. Here's my code:

public class HomeFragment extends Fragment {

 public HomeFragment() {
     // Required empty public constructor
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                          Bundle savedInstanceState) {

     View rootView = inflater.inflate(R.layout.fragment_home, container, false);

     // Define webview stuff
     DataSelector dataSelector = new DataSelector(rootView);
     dataSelector.getData();

-

public class DataSelector {
    public View mRootView;

    public DataSelector(View RootView){
        mRootView = RootView;
    }

    TextView resultView = (TextView) mRootView.findViewById(R.id.result);

    public void getData(){
       ...
1

There are 1 answers

1
fdreger On

The initialization code for attributes is always run BEFORE the constructor. So mRootView is empty when resultView is initialized.