Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from EditText Android

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 Fragments or am I missing something?

like image 448
Efaz Avatar asked Dec 27 '25 19:12

Efaz


1 Answers

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());
        }
    });
like image 198
Onik Avatar answered Dec 30 '25 12:12

Onik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!