vendredi 1 janvier 2016

Exception Handling in If statement?

I'm struggling to create a very simple app. There are Product Names with matching Product Numbers. User enters a Number and the corresponding Name appears.

editTextField1 = the number user types

button1 = the search button

editTextField2 = the product name appears

Now my code is working but there is only one problem, when the user doesn't enter anything and clicks on button1 the app crashes. So I need some sort of exception handler maybe? Im struggling to get my head around it. I know how I'm coding, by declaring loads of variables, is long-winded lol.

public class MainActivity extends AppCompatActivity {

private Button button1;
private EditText editText1;
private EditText editText2;
private int a = 123;
private String b = "TV";
private int c  = 333;
private String d = "Radio";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1 = (Button) findViewById(R.id.button1);
    editText1 = (EditText) findViewById(R.id.editText1);
    editText2 = (EditText) findViewById(R.id.editText2);

    View.OnClickListener myOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            double pNumber = Double.parseDouble(editText1.getText().toString());
            if(pNumber == a){
                editText2.setText(b);
            }
           else if (pNumber == c){
                editText2.setText(d);
            }
            else
                editText2.setText("Invalid Product Number");
            }


    };

    button1.setOnClickListener(myOnClickListener);

Aucun commentaire:

Enregistrer un commentaire