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

// すべてのユーザー入力 // // Fields Validation // を入れ 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

私がお勧めするのは、TextWatcher の使用です。このようにすると、次の手順が役立つと思います。

まず、android.text.TextWatcher を実装します。

次に、必要なメソッドを実装します。最も重要なのは、 afterTextChanged(Editable) です。

3番目に、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 に答える
0

これは予期される動作です。クラスをEditText拡張することに注意してください。TextViewそして、あなたが使用しているメソッドはfromsetError(CharSequence)によって継承されています。EditTextTextView

これが目的として設計されていることは次のとおりです。

TextView の右側の複合ドローアブルを「エラー」アイコンに設定し、TextView にフォーカスがあるときにポップアップに表示されるエラー メッセージを設定します。キー イベントによって TextView のテキストが変更されると、アイコンとエラー メッセージは null にリセットされます。エラーが null の場合、エラー メッセージとアイコンはクリアされます。

クリックが発生すると、EditText はフォーカスを失い、フォーカスが回復するまで待機してエラーを送信します。

エラーが発生したことをユーザーに示すには、 を呼び出す代わりに、setError(CharSequence)を使用して EditText 内に警告テキストを設定できますmyEditText.setText("Required")requestFocus()の直後に EditText を呼び出してエラーを表示することもできますがsetError(CharSequence)、2 つ以上のエラーが発生した場合にこれがどのように動作するかはわかりません。

于 2013-07-20T19:04:45.237 に答える