Search code examples
javaandroidsqliteif-statementandroid-sqlite

How do i add an if-else statement in these lines of code?


I want to make sure my user fill in all the spaces provided in the interface before they are qualified to create an account. Where can I add the if-else statement in these lines of codes? I am doing this to ensure the user inserted all the data before going to the profile page. Please help me guys.

 createacc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, profile.class);
            startActivity(intent);
            getData();
        }
    });
}

private void getData() {
    email = "" + Pemail.getText().toString().trim();
    name = "" + Pname.getText().toString().trim();
    age = "" + PAge.getText().toString().trim();
    phone = "" + Pphone.getText().toString().trim();
    preferenceselected = "" + Ppreferenceselected.getText().toString().trim();
    password = "" + Ppassword.getText().toString().trim();

    String timeStamp = "" + System.currentTimeMillis();

    boolean id = dbHelper.insertInfo(
            "" + imageUri,
            "" + email,
            "" + name,
            "" + age,
           "" + phone,
            "" + preferenceselected,
            "" + password,
            ""+timeStamp,
            ""+timeStamp

    );

        Toast.makeText(this, "Account Created", Toast.LENGTH_SHORT).show();
}

Solution

  • Right after you trim all the values contained in the EditTexts, check if any of them is empty:

    email = Pemail.getText().toString().trim();
    name = Pname.getText().toString().trim();
    age = PAge.getText().toString().trim();
    phone = Pphone.getText().toString().trim();
    preferenceselected = Ppreferenceselected.getText().toString().trim();
    password = Ppassword.getText().toString().trim();
    if (email.isEmpty() || name.isEmpty() || age.isEmpty() || phone.isEmpty() || preferenceselected.isEmpty() || password.isEmpty()) {
        Toast.makeText(this, "Please fill all the info...", Toast.LENGTH_SHORT).show();
        return; 
    }
    String timeStamp = "" + System.currentTimeMillis();
    ......................................................
    

    The expression:

    email.isEmpty() || name.isEmpty() || age.isEmpty() || phone.isEmpty() || preferenceselected.isEmpty() || password.isEmpty()
    

    will return true if one of the operands returns true and will not check the rest because of short circuit evaluation and in such a case a Toast will be displayed and the code will return without proceeding with the creation of the account, so no need for else....

    Also there is no need for all these "" + ... concatenations because the result of toString().trim() is a String.