-1

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

我有 8 个 EditText 框和 2 个微调器,并且TextView拥有ListView. 在 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

4 回答 4

0

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

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

验证功能将是这样的

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

}

于 2012-12-18T08:46:40.860 回答
0

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

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

}

希望这可以帮助。

于 2012-12-18T07:58:00.433 回答
0

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

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

于 2012-12-18T08:01:58.620 回答
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 中做什么,即在此处输入您的电子邮件ID。

编码快乐!!

于 2012-12-18T08:13:28.997 回答