Andrew T Andrew T - 25 days ago 17
Java Question

Android fragment findViewByID returns null

I have a fragment where I would like to connect the takePhotoButton variable to the button in the fragment_send layout but the findViewById returns null. How can this be solved?

public class SendFragment extends Fragment {

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

FrameLayout ll = (FrameLayout) inflater.inflate(R.layout.fragment_send, container, false);

Button takePhotoButton = (Button)rootView.findViewById(R.id.take_photo);
takePhotoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getFileUri();
i.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
startActivityForResult(i, 10);
}
});
detail1 = (EditText)rootView.findViewById(R.id.etDetail1);

return ll;
}

Answer

Change these lines

Button takePhotoButton = (Button)rootView.findViewById(R.id.take_photo);
...
detail1 = (EditText)rootView.findViewById(R.id.etDetail1);

with

Button takePhotoButton = (Button)ll.findViewById(R.id.take_photo);
...
detail1 = (EditText)ll.findViewById(R.id.etDetail1);
Comments