Home > Blockchain >  how to pass a decimal value using number type Edittext in Android Studio?
how to pass a decimal value using number type Edittext in Android Studio?

Time:10-19

I'm trying to pass a decimal number (edtNumber) to a Toast but when i running the app the number doesn't appear in the Toast.

public class MainActivity extends AppCompatActivity {

    private TextView txtDate;
    private Button addBtn;
    private EditText edtNumber;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtDate = findViewById(R.id.txtDate);
        addBtn = findViewById(R.id.addBtn);
        edtNumber = findViewById(R.id.edtNumber);
        String weight = edtNumber.getText().toString();

        SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy HH:mm:ss");
        String currentDateAndTime = sdf.format(new Date());
        txtDate.setText(currentDateAndTime);


        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "Weight:"  weight   "\n"   currentDateAndTime, Toast.LENGTH_SHORT).show();
            }
        });

CodePudding user response:

Problem


The problem is in this line:

String weight = edtNumber.getText().toString();

you care calling that line of code as soon as the activity is created where it has no value. You want to get value only if the button is clicked.

Solution


You will have to add this line to your onClick method. Finally, the code will look like this:

public class MainActivity extends AppCompatActivity {

    private TextView txtDate;
    private Button addBtn;
    private EditText edtNumber;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtDate = findViewById(R.id.txtDate);
        addBtn = findViewById(R.id.addBtn);
        edtNumber = findViewById(R.id.edtNumber);
        String weight = "";

        SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy HH:mm:ss");
        String currentDateAndTime = sdf.format(new Date());
        txtDate.setText(currentDateAndTime);


        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                weight = edtNumber.getText().toString()
                Toast.makeText(MainActivity.this, "Weight:"  weight   "\n"   currentDateAndTime, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
  • Related