2013-07-20 49 views
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(); 
     } 
    } 

回答

1

嘗試把//所有的用戶輸入// //字段的驗證 // public void SubmitData(View view)和使用if{} else{}

您還將獲得null pointer Exception,因爲你沒有給予任何價值到

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

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

    } 
+0

當我這樣做,我只要一按一下按鈕,應用程序崩潰。任何理由爲什麼或如何修復? –

+0

投擲nullpointerexception –

+0

@sys_debug看到我更新的答案!如果仍然拋出任何異常讓我知道! –

0

這是預期的行爲。請注意,EditText擴展了TextView類。而且,您正在使用的方法:setError(CharSequence)EditTextTextView繼承。

下面是它的目的是做:

設置的TextView的右手複合繪製的「錯誤」 圖標,設置要顯示在彈出時 錯誤消息TextView有焦點。當任何關鍵事件導致TextView文本更改時,圖標和錯誤消息將被重置爲 null。如果 錯誤爲空,則錯誤消息和圖標將被清除。

當遇到點擊後,的EditText失去焦點,並等待,直到它重新獲得焦點張貼錯誤。

要向用戶顯示發生錯誤,而不是調用setError(CharSequence),可以使用myEditText.setText("Required")在EditText中設置警告文本。您也可以在EditText上撥打requestFocus()以在setError(CharSequence)之後立即顯示錯誤,但我不確定在2個或更多錯誤情況下這會如何表現。

0

我會推薦做的是使用TextWatcher。如果你這樣說,我相信這些措施將有助於:

一是落實android.text.TextWatcher

其次,實施必要的方法,最重要的是,afterTextChanged(編輯)

三,爲您的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){ 
      ... 
    } 
}