按钮上的验证

时间:2012-12-18 07:40:31

标签: java android

我在我的应用程序中使用了一个保存按钮。当我点击保存按钮时,我希望它验证每个字段并显示错误消息,如"请输入此字段","请在此字段中输入正确的格式"或"请选择此"。

我有8个EditText框和2个微调框,而TextViewListView。在Android中,如何在每个字段上使用字段验证,并在验证每个字段后成功保存数据。

我的java代码是:

    public class non_ticket_task extends Activity implements OnItemSelectedListener{


    public static String complain_date;
    public static String complain_time;
    public static String job_performed;
//  public static String time;
    public static String next_due_on;
    static TelephonyManager tm; 

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    TextView cus_name_txt;
    EditText complain_date_txtbx;
    EditText complain_time_txtbx;
    EditText job_performed_txtbx;
    EditText date_txtbx;
    EditText lat_txtbx;
    EditText lon_txtbx;
    EditText next_due_on_txtbx;
    Button btnadd;

    // url to create new product
    private static String url_create_task = "http://192.168.2.1/android_connect/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.non_ticket_task);   

      this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
      tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

   // Buttons
      btnadd = (Button) findViewById(R.id.addbtn);

   // button click event
      btnadd.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View view) {
              // creating new task in background thread
              new CreateNewTask().execute();
          }
      });


       cus_name_txt = (TextView)findViewById(R.id.textView1);
        cus_name_txt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Onclick_click1(cus_name_txt);


            }
        }); 


        complain_date_txtbx = (EditText) findViewById(R.id.complain_date_txt);
        complain_date_txtbx.setText(non_ticket_task.complain_date);

        complain_time_txtbx = (EditText) findViewById(R.id.complain_time_txt);
        complain_time_txtbx.setText(non_ticket_task.complain_time);

        job_performed_txtbx = (EditText) findViewById(R.id.job_performed_txt);
        job_performed_txtbx.setText(non_ticket_task.job_performed);

        date_txtbx = (EditText) findViewById(R.id.date_txt);
        date_txtbx.setText(" "
                + String.valueOf(java.text.DateFormat.getDateTimeInstance()
                        .format(Calendar.getInstance().getTime())));


        MyLocation loc = new MyLocation(this.getApplicationContext());
        lon_txtbx = (EditText) findViewById(R.id.lon_txt);
        lon_txtbx.setText(String.valueOf(loc.lon));
        lat_txtbx = (EditText) findViewById(R.id.lat_txt);
        lat_txtbx.setText(String.valueOf(loc.lat));

        next_due_on_txtbx = (EditText) findViewById(R.id.next_due_on_txt);
        next_due_on_txtbx.setText(non_ticket_task.next_due_on);



        Spinner status = (Spinner) findViewById(R.id.status_spinner);
     // Create an ArrayAdapter using the string array and a default spinner layout
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
             R.array.Status_array, android.R.layout.simple_dropdown_item_1line);
     // 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
     status.setAdapter(adapter);


     Spinner severity = (Spinner) findViewById(R.id.severity_spinner);
     // Create an ArrayAdapter using the string array and a default spinner layout
     ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
             R.array.Severity_array, android.R.layout.simple_dropdown_item_1line);
     // Specify the layout to use when the list of choices appears
     adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     // Apply the adapter to the spinner
     severity.setAdapter(adapter1);


    }


    public void onItemSelected(AdapterView<?> parent, View view, 
            int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        // parent.getItemAtPosition(pos)
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }

    public void Onclick_click1(final TextView cus_name_txt)
    {
        final TextView txtbx = (TextView) cus_name_txt;

        if(cus_name_txt.getId()==R.id.textView1)
        {

            final CharSequence[] items = {"Ali Asghar","Ali Shah","Tamseel","Bilal","Daniyal","Muzamil","Faraz","Uzair","Mohsin","Mehran","Babar","Ameen","Zeeshan","Maqsood","Hasan","Taqi","Talib","Asif","Mudasir"};
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Customers Name");
            //builder.setI
            builder.setItems(items, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int item) {
                    //Toast.makeText(getApplicationContext(), con.get(item).getCountrName(), Toast.LENGTH_SHORT).show();
                    txtbx.setText(items[item]);
                    System.out.println("Item is: "+items[item]);
                    /*CONTRY_ID = con.get(item).getCountryId();
                    stateET.requestFocus();*/
               }
            });

            builder.show();

        }

} 

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewTask extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(non_ticket_task.this);
            pDialog.setMessage("Saving Details..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating task
         * */
        protected String doInBackground(String... args) {
            String cus_name = cus_name_txt.getText().toString();
            String complain_date = complain_date_txtbx.getText().toString();
            String complain_time = complain_time_txtbx.getText().toString();
            String job_performed = job_performed_txtbx.getText().toString();
            String date = date_txtbx.getText().toString();
            String next_due_on = next_due_on_txtbx.getText().toString();
            String lat = lat_txtbx.getText().toString();
            String lon = lon_txtbx.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("cus_name", cus_name));
            params.add(new BasicNameValuePair("complain_date", complain_date));
            params.add(new BasicNameValuePair("complain_time", complain_time));
            params.add(new BasicNameValuePair("job_performed", job_performed));
            params.add(new BasicNameValuePair("date", date));
            params.add(new BasicNameValuePair("next_due_on", next_due_on));
            params.add(new BasicNameValuePair("lat", lat));


            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_task,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), My_Task.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }

4 个答案:

答案 0 :(得分:0)

如果我非常了解您,您只需确保向用户提供反馈,以便在EditText中输入内容。如果这是你想要的,那么你只需要检查EditText.getText的长度,如下所示:

if (cus_name_txt.getText().Lenght()==0){
//Your message here

}

希望这有帮助。

答案 1 :(得分:0)

在onPreExecute中,您可以进行验证。如果字段为空(或错误),则将该字段设置为错误消息。如果有一个或多个无效字段,则取消AsyncTask并显示错误。用户修复错误后,可以再次按“保存”。

您应该从onPreExecute中的字段中获取字符串,而不是在doInBackground中,因为您无法从该方法对Ui进行修改。

答案 2 :(得分:0)

坦率地说,验证过程在很大程度上取决于您要验证的内容和方式。例如,如果要在离开焦点后或仅在单击“提交”按钮后验证edittext的文本。 TextWatchers可以实现快速且用户友好的验证。但是,如果要在单击按钮时进行验证,则可以使用类似

的功能
boolean void validateInput(){
boolean retStatus=false;
if((textView1.getText().length()==0 ||  textView1.getText().equals("") && (any other condition )){
   retStatus=true;
   textView1.setError("You have entered wrong value in textView 1");
}
//similarly for other controls
------ 
-----
--

return retStatus;
}

如果您想立即使用错误检测,错误检查(和更正)将会很快,而上述方法可能会显示“一次性”错误。您可以决定适合您的用户。

为了减少用户输入错误,请使用edittexts的文本类型,即使用editText的数字作为电话号码,使用姓名的字母或输入电子邮件的emailid等。使用提示指示用户在EditText中应该做什么,即输入您的电子邮件在这里。

快乐编码!!

答案 3 :(得分:0)

你可以像这样创建一个validatefields()函数并像这样调用这个函数

 if(validate()){
      new CreateNewTask().execute() 
 }
 else{
    showErrorMsg(msg);
 }

其中validate函数将是这样的

private boolean validate(){
boolean retStatus=false;

if((textView1.getText().length()==0 ||  textView1.getText().equals("") ){
  retStatus=false; 
  msg = "Please fill TextView 1";

}
else if ( ---check other 9  condition in the same way--)

}

if ( !msg.equals("")){
     return false;
   }
else {
     return true;
}

}