Issue
I have bunch of EditText
fields and I am trying to get their values. But it is returning empty strings. Here is my code:
public class add_product_fragment extends Fragment implements AdapterView.OnItemSelectedListener{
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_product, container, false);
mName = view.findViewById(R.id.productName);
productName = mName.getText().toString().trim();
mPrice = view.findViewById(R.id.productPrice);
productPrice = mPrice.getText().toString().trim();
mDescription = view.findViewById(R.id.productDescription);
productDescription = mDescription.getText().toString().trim();
mQuantity = view.findViewById(R.id.productQuantity);
productQuantity = mQuantity.getText().toString().trim();
addToInventory = view.findViewById(R.id.addToInventoryBtn);
addToInventory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println(productName + ", " + productDescription + ", " + productType
+ ", " + productPrice + ", " + productQuantity);
}
});
return view;
}
It is not working because of Fragment
s or am I missing something?
Solution
A user can interact with Activity
's/Fragment
's UI only after onResume()
returns. So having something like yourEditText.getText().toString()
in the Fragment
's onCreateView()
lifecycle method would unavoidably result in an empty string.
You should "retrieve" the EditTexts'
values after the user interaction, meaning the addToInventory
's onClick
listener should look as follows:
addToInventory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println(
mName.getText().toString().trim() + ", " +
mDescription.getText().toString().trim() + ", " +
mProductType.getText().toString().trim() + ", " +
mPrice.getText().toString().trim() + ", " +
mQuantity.getText().toString().trim());
}
});
Answered By - Onik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.