sys_debug
sys_debug

Reputation: 4003

android input validation not working as expected

I am trying to perform simple form validation whereby I use EditText.setError() to notify the user of the wrong input or blank field. Unfortunately, when I do that it only shows error when I click on the field again after incomplete form submission. This is weird because I want it to show as soon as I click button and form incomplete.

I believe it has something to do with the placement of the code that does the validation? Following is my code:

public class AddDiscountActivity extends Activity implements OnItemSelectedListener{

    String shopCategory;
    Spinner spinner;

    String shopName;
    String shopCity;
    String shopLocation;
    String discountRate;
    String discountDuration;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.adddiscount_activity);
         spinner = (Spinner) findViewById(R.id.categoriesSpinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.categoriesArray, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
    }

    public void SubmitData(View view)
    {

        new PostDataAsyncTask().execute();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
    {
        // TODO Auto-generated method stub

        shopCategory = spinner.getItemAtPosition(pos).toString();
        Log.v("SHOP CATEGORY***********: ", shopCategory);
    }





    public class PostDataAsyncTask extends AsyncTask<String, String, String> 
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            progressDialog= ProgressDialog.show(AddDiscountActivity.this, "Please Wait","Update Ads listings", true);

            //do initialization of required objects objects here                
        };  

        @Override
        protected String doInBackground(String... strings) {
            // TODO Auto-generated method stub
            try {
                postAdData();

            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

         @Override
         protected void onPostExecute(String lenghtOfFile) {
             // do stuff after posting data
             super.onPostExecute(lenghtOfFile);
             progressDialog.dismiss();
             //Intent intent = new Intent(MainActivity.this, ThankYouAcitivty.class);
            // startActivity(intent);

         }

    }

    private void postAdData() throws JSONException{
        try{
            // url where the data will be posted
            String postReceiverUrl = "http://hye.com/displaypost.php";

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            //All user input
            EditText shopNameEditText = (EditText)findViewById(R.id.shopName);
            EditText shopLocationEditText = (EditText)findViewById(R.id.shopLocation);
            EditText shopCityEditText = (EditText)findViewById(R.id.shopCity);
            EditText discountRateEditText = (EditText)findViewById(R.id.shopDiscount);
            EditText discountDurationEditText = (EditText)findViewById(R.id.shopDiscountDuration);

            shopNameEditText.getText().toString();
            shopLocationEditText.getText().toString();
            shopCityEditText.getText().toString();
            discountRateEditText.getText().toString();
             discountDurationEditText.getText().toString();


            /*******Fields Validation*********/
             if(shopNameEditText.getText().toString().length() == 0)
                 shopNameEditText.setError("يجب ادخال اسم المحل");
             if(shopLocationEditText.getText().toString().length() == 0)
                 shopLocationEditText.setError("يجب ادخال العنوان");
             if(shopCityEditText.getText().toString().length() == 0)
                 shopCityEditText.setError("يجب ادخال المدينة");
             if(discountRateEditText.getText().toString().length() == 0)
                 discountRateEditText.setError("يجب ادخال نسبة التخفيض");


            /*********************************/

            nameValuePairs.add(new BasicNameValuePair("name", shopName));
            nameValuePairs.add(new BasicNameValuePair("location", shopLocation));
            nameValuePairs.add(new BasicNameValuePair("city", shopCity));
            nameValuePairs.add(new BasicNameValuePair("rate", discountRate));
            nameValuePairs.add(new BasicNameValuePair("duration", discountDuration));
            nameValuePairs.add(new BasicNameValuePair("category", shopCategory));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

            // execute HTTP post request

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {

                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v("", "Response: " +  responseStr);

                // you can add an if statement here and do other actions based on the response
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Upvotes: 1

Views: 1190

Answers (3)

Tarsem Singh
Tarsem Singh

Reputation: 14199

try by putting // All user input // // Fields Validation // inside public void SubmitData(View view) and use if{} else{}

you will Also get null pointer Exception because you are not assigning any value to

String shopName;   
String shopCity;
String shopLocation; 
String discountRate;      
String discountDuration;

so your public void SubmitData(View view) should be like :

  public void SubmitData(View view)
    {
 //All user input
            EditText shopNameEditText = (EditText)findViewById(R.id.shopName);
            EditText shopLocationEditText = (EditText)findViewById(R.id.shopLocation);
            EditText shopCityEditText = (EditText)findViewById(R.id.shopCity);
            EditText discountRateEditText = (EditText)findViewById(R.id.shopDiscount);
            EditText discountDurationEditText = (EditText)findViewById(R.id.shopDiscountDuration);
         if(shopNameEditText.getText().toString().length() == 0)
             shopNameEditText.setError("يجب ادخال اسم المحل");
         else if(shopLocationEditText.getText().toString().length() == 0)
             shopLocationEditText.setError("يجب ادخال العنوان");
         else if(shopCityEditText.getText().toString().length() == 0)
             shopCityEditText.setError("يجب ادخال المدينة");
         else if(discountRateEditText.getText().toString().length() == 0)
             discountRateEditText.setError("يجب ادخال نسبة التخفيض");
          else
                 {
                shopName = shopNameEditText.getText().toString();
                shopLocation = shopLocationEditText.getText().toString();
                shopCity = shopCityEditText.getText().toString();
                discountRate = discountRateEditText.getText().toString();
                discountDuration = discountDurationEditText.getText().toString();

                   new PostDataAsyncTask().execute();
                 }

    }

Upvotes: 1

Vikram
Vikram

Reputation: 51571

This is the expected behavior. Note that EditText extends the TextView class. And, the method that you are using: setError(CharSequence) is inherited by EditText from TextView.

Here is what it is designed to do:

Sets the right-hand compound drawable of the TextView to the "error" icon and sets an error message that will be displayed in a popup when the TextView has focus. The icon and error message will be reset to null when any key events cause changes to the TextView's text. If the error is null, the error message and icon will be cleared.

When the click is encountered, the EditText loses focus and waits until it regains focus to post the error.

To show the user that an error has occured, instead of calling setError(CharSequence), you can set warning text inside the EditText using myEditText.setText("Required"). You can also call requestFocus() on the EditText to show the error immediately after setError(CharSequence), but I am not sure how this would behave in case of 2 or more errors.

Upvotes: 0

Mike M
Mike M

Reputation: 752

What I would recommend doing is using TextWatcher. If you do it this way, I believe these steps will help:

First, implement android.text.TextWatcher

Second, implement the necessary methods, most importantly, afterTextChanged(Editable)

Third, add textlisteners for your EditText's

For example...

EditText shopNameEditText = (EditText)findViewById(R.id.shopName);
shopNameEditText.addTextChangedListener(this);

@Override
public void afterTextChanged(Editable s) {
     //check validation
     if(shopNameEditText.getText().toString().length() == 0){
          ...
     }
}

Upvotes: 0

Related Questions