jeudi 16 juillet 2015

Android: How can I keep empty EditText fields out of a randomized count?

I am working on an Android app in which there are five EditText in one activity.

Users can fill out the EditText fields they need and when they press a Button, they'll get a randomized answer on a single TextView in the second activity.

Let's say a user only fills out 3 EditText fields, how can I keep empty ones out of the random count?

Please help! Thanks!

Here's the code:

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    EditText choiceOne;
    EditText choiceTwo;
    EditText choiceThree;
    EditText choiceFour;
    EditText choiceFive;
    Button mainButton;

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

        choiceOne = (EditText) findViewById(R.id.inputOne);
        choiceTwo = (EditText) findViewById(R.id.inputTwo);
        choiceThree = (EditText) findViewById(R.id.inputThree);
        choiceFour = (EditText) findViewById(R.id.inputFour);
        choiceFive = (EditText) findViewById(R.id.inputFive);

        mainButton = (Button) findViewById(R.id.inputButton);
        mainButton.setOnClickListener(this);




    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public void onClick(View view)
    {

        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        intent.putExtra("choiceOne", choiceOne.getText().toString());
        intent.putExtra("choiceTwo", choiceTwo.getText().toString());
        intent.putExtra("choiceThree", choiceThree.getText().toString());
        intent.putExtra("choiceFour", choiceFour.getText().toString());
        intent.putExtra("choiceFive", choiceFive.getText().toString());
        startActivity(intent);


    }
}

SecondActivity.java

public class SecondActivity extends Activity {

    TextView answerDisplay;

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

        answerDisplay = (TextView) findViewById(R.id.display);


        Intent intent = getIntent();
        String[] choice = {intent.getStringExtra("choiceOne"), intent.getStringExtra("choiceTwo"),
                intent.getStringExtra("choiceThree"), intent.getStringExtra("choiceFour"),
                intent.getStringExtra("choiceFive")};
        int choiceRandom = (int) (Math.random() *5 );

        answerDisplay.setText(choice[choiceRandom]);

    }




Aucun commentaire:

Enregistrer un commentaire