1

我正在尝试执行简单的表单验证,我使用 EditText.setError() 来通知用户输入错误或空白字段。不幸的是,当我这样做时,只有在提交不完整的表单后再次单击该字段时才会显示错误。这很奇怪,因为我希望它在我单击按钮并形成不完整时立即显示。

我相信这与进行验证的代码的放置有关吗?以下是我的代码:

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();
        }
    }
4

3 回答 3

1

尝试将 // 所有用户输入 // // 字段验证// 放入 public void SubmitData(View view)并使用if{} else{}

你也会得到null pointer Exception,因为你没有分配任何价值

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

所以public void SubmitData(View view) 应该是这样的:

  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();
                 }

    }
于 2013-07-20T19:12:43.847 回答
0

这是预期的行为。请注意,EditText扩展TextView类。而且,您正在使用的方法:setError(CharSequence)EditTextfrom继承TextView

这是它的设计目的:

将 TextView 的右侧复合可绘制对象设置为“错误”图标,并设置当 TextView 获得焦点时将在弹出窗口中显示的错误消息。当任何关键事件导致 TextView 的文本发生更改时,图标和错误消息将重置为 null。如果错误为空,则错误消息和图标将被清除。

遇到单击时,EditText 失去焦点并等到它重新获得焦点以发布错误。

为了向用户显示发生了错误setError(CharSequence),您可以使用在 EditText 中设置警告文本,而不是调用myEditText.setText("Required")。您也可以调用requestFocus()EditText 以在 之后立即显示错误setError(CharSequence),但我不确定如果出现 2 个或更多错误,这将如何表现。

于 2013-07-20T19:04:45.237 回答
0

我建议做的是使用 TextWatcher。如果你这样做,我相信这些步骤会有所帮助:

首先,实现android.text.TextWatcher

二、实现必要的方法,最重要的是afterTextChanged(Editable)

第三,为您的 EditText 添加文本监听器

例如...

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

@Override
public void afterTextChanged(Editable s) {
     //check validation
     if(shopNameEditText.getText().toString().length() == 0){
          ...
     }
}
于 2013-07-20T19:04:56.653 回答