-1

I am using a save button in my application. When I click on save button, I want it to validate each field and display an error message like "Please enter this field", "Please enter in correct format in this field" or "Please select this".

I have 8 EditText boxes and 2 spinners and on TextView having ListView. In Android, how to use field validation on every field and after validating each field it save data successfully.

My java code is:

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

    }
Matthieu
  • 16,103
  • 10
  • 59
  • 86
Mona
  • 267
  • 1
  • 4
  • 9
  • You can use TextWatcher. Check this http://stackoverflow.com/questions/2763022/android-how-can-i-validate-edittext-input – Rahul Dec 18 '12 at 07:53
  • @rahulkapoor He wants to sheck after "save" pressing, not after every change in the field. – Gangnus Dec 18 '12 at 07:58
  • Where is the problem? Can't you check fields or save or output the error message? – Gangnus Dec 18 '12 at 07:59

4 Answers4

0

Hi if I understand you very well you just want to make sure you give feedback to users to type something in the EditText. If that is what you want, then you only need to check the lenght of the EditText.getText like so:

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

}

Hope this helps.

0

In onPreExecute you do the validations. If a field is empty(or wrong) you set to that field an error message. If there are one or more invalid fields, you cancel the AsyncTask and show the error. After the user fixes the errors, it can press Save again.

You should take the string from the fields in onPreExecute, not in doInBackground, because you cannot make modifications in the Ui from that method.

Emil Pana
  • 468
  • 5
  • 14
0

Frankly speaking the validation process largely depends upon what you want to validate and how. For example if you want to validate the text of an edittext just after leaving the focus or only after clicking the submit button. TextWatchers can serve the purpose for a fast and user friendly validation. However if you want to validate on click of a Button, You can have a function like

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

If you want to use immediate error detection the error checking (and correction) will be fast instead methods like above can show "all at once" errors. You can decide whichever suits to your users.

For reducing user input errors use text type for edittexts i.e. use numeric for editText for phone number, alphabets for Names or type emailid for emails etc. Use hints to indicate users what they are supposed to do in that EditText i.e. enter your email id here.

Happy Coding!!

Amit
  • 13,134
  • 17
  • 77
  • 148
0

You can make a function validatefields() like this and call this function in like this

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

where validate function will be like this

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

}

neeraj t
  • 4,654
  • 2
  • 27
  • 30