Henji
Henji

Reputation: 33

Can't figure out how to assign multiple EditText to variable

This code crashes my android studio app and I'm not sure why. I am assign the lotteryInputs to lottery but it just closes my app. It works if I remove 2 and 3 lottery and lotteryInput(s) however.

String lottery, lottery2, lottery3;
    
    EditText lotteryInput;
    EditText lotteryInput2;
    EditText lotteryInput3;

    Button subButton;

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

        lotteryInput = (EditText) findViewById(R.id.lotteryInput);
        subButton = (Button) findViewById(R.id.playLottery);
        subButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lottery = lotteryInput.getText().toString();
                lottery2 = lotteryInput2.getText().toString();
                lottery3 = lotteryInput3.getText().toString();

                Toast.makeText(getApplicationContext(), lottery, Toast.LENGTH_SHORT).show();
            }
        });
    }

Particularly the lines:

lottery2 = lotteryInput2.getText().toString();
lottery3 = lotteryInput3.getText().toString();

crashes it

Upvotes: 1

Views: 37

Answers (1)

Mohammed Abid Nafi
Mohammed Abid Nafi

Reputation: 519

I can see that you haven't called the EditText lotteryInput2 and 3 so to fix that just follow the below code

String lottery, lottery2, lottery3;

EditText lotteryInput;
EditText lotteryInput2;
EditText lotteryInput3;

Button subButton;

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

    lotteryInput = (EditText) findViewById(R.id.lotteryInput);
    lotteryInput2 = (EditText) findViewById(R.id.youridforsecondEditText);//AddThis
    lotteryInput3 = (EditText) findViewById(R.id.youridforThirdEditText);//AddThis
    subButton = (Button) findViewById(R.id.playLottery);
    subButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            lottery = lotteryInput.getText().toString();
            lottery2 = lotteryInput2.getText().toString();
            lottery3 = lotteryInput3.getText().toString();

            Toast.makeText(getApplicationContext(), lottery, Toast.LENGTH_SHORT).show();
        }
    });
}

Upvotes: 2

Related Questions