DE_CR DE_CR - 1 month ago 8
Android Question

Unfortunately, app has stopped,how can I make this work onCreateView?

Previously, I had a similar issue, app crashes when trying to access (or findByID), it turned out, I've put the textview in the wrong method, Now I have only one method, and I am working with a fragment, the method

onCreateView
and my app keeps crashing:

public class InfoFragment extends Fragment {


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


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

TextView n = (TextView) getView().findViewById(R.id.nama);
n.setText("Some String");

// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_info, container, false);
}

}


Originally, I had the line looking like this :

TextView n = (TextView) findViewById(R.id.nama);


However,the compiler gave me an error saying it can't find the method
findViewById
, so some research showed that I should add
getView()
, I did, and the error disappeared, but now the app is crashing, any ideas?

Answer
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.fragment_info, container, false);

   TextView n = (TextView) view.findViewById(R.id.nama);
   n.setText("Some String");

   return view;
} 

You don't have a view yet in that part of code. Inflate it first and use after.