如何在Android中创建RequiredFieldValidattion?

时间:2015-05-12 10:37:49

标签: java android

这是我的代码。它看起来有点复杂,但它工作得很好。我只是想知道当我点击btnCreateProduct时我该如何创建它应该验证所需的编辑文本字段以及在哪里添加这些代码?

package com.prinsapps.whatson;


import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.prinsapps.whatson.Addevent.CreateNewProduct;



public class Addevent extends Activity implements OnClickListener {
  private ImageButton ib;
  private Calendar cal;
  private int day;
  private int month;
  private int year;
  private EditText et;

//Progress Dialog
  private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
  EditText inputName;
  EditText inputDesc;
  EditText inputCountry;
  EditText inputdate;
  EditText inputLink;
  EditText inputOrg;
// url to create new product
  private static String url_create_product = "http://-----------";

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

@Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.add_event);

//Edit Text
  inputName = (EditText) findViewById(R.id.inputName);
  inputDesc = (EditText) findViewById(R.id.inputDesc);
  inputCountry = (EditText) findViewById(R.id.inputCountry);
  inputdate = (EditText) findViewById(R.id.inputdate);
  inputLink = (EditText) findViewById(R.id.inputLink);
  inputOrg = (EditText) findViewById(R.id.inputOrg);

// mDateButton = (Button) findViewById(R.id.date_button);
  ib = (ImageButton) findViewById(R.id.imageButton1);
  cal = Calendar.getInstance();
  day = cal.get(Calendar.DAY_OF_MONTH);
  month = cal.get(Calendar.MONTH);
  year = cal.get(Calendar.YEAR);
  et = (EditText) findViewById(R.id.inputdate);
      ib.setOnClickListener(this);

// Create button
  Button btnCreateProduct = (Button)  
  findViewById(R.id.btnCreateProduct);

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

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


@Override
  public void onClick(View v) {
  showDialog(0);
  }

@Override
@Deprecated
  protected Dialog onCreateDialog(int id) {
  return new DatePickerDialog(this, datePickerListener, year, month, day);
}

  private DatePickerDialog.OnDateSetListener datePickerListener = new
  DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int selectedYear,
  int selectedMonth, int selectedDay) {
  et.setText(selectedYear+"/"+(selectedMonth+1)+"/"+selectedDay);
}
};

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

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

    /**
     * Creating product
     * 
     * */
      protected String doInBackground(String... args) {
          String name = inputName.getText().toString();
          String description = inputDesc.getText().toString();
          String country = inputCountry.getText().toString();
          String date = inputdate.getText().toString();
          String link = inputLink.getText().toString();
          String org = inputOrg.getText().toString();

        // Building Parameters
          List<NameValuePair> params = new ArrayList<NameValuePair>();
          params.add(new BasicNameValuePair("name", name));
          params.add(new BasicNameValuePair("description", description));
          params.add(new BasicNameValuePair("country", country));
          params.add(new BasicNameValuePair("date", date));
          params.add(new BasicNameValuePair("link", link));
          params.add(new BasicNameValuePair("org", org));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "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(),
                AllProductsActivity.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();
    }

}
  }

3 个答案:

答案 0 :(得分:0)

正如我假设的那样,如果你创建了一个产品,你不想让你的Textfield为空,我建议检查你的Strings的{​​{1}}为空或者空。

这可能是这样的:

EditTexts

我建议将此添加到您的if(inputName.getText().equals("") || inputName.getText().equals(null)){ //Maybe show some message, that the given field ist required to be filled out } 方法中,或者编写一个额外的方法来检查EditText是否为空并返回一个布尔值。这看起来像这样:

onClick()

然后在创建新产品之前检查每个public boolean notEmpty(EditText et){ if(et.getText().equals("") || et.getText().equals(null)){ return false; } return true; } et。

答案 1 :(得分:0)

使用editText观察器

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
//Add your validations here
            }
        });

答案 2 :(得分:0)

是的,现在工作正常

    @Override
    public void onClick(View view) {

        if (  ( !inputName.getText().toString().equals("")) && 
              ( !inputDesc.getText().toString().equals("")) &&
              ( !inputCountry.getText().toString().equals("")) &&
              ( !inputdate.getText().toString().equals(""))
            )
        {
            // creating new product in background thread
            new CreateNewProduct().execute();
        }
        else if ( ( !inputName.getText().toString().equals("")) )
        {
            Toast.makeText(getApplicationContext(),
                    "Please Enter Event Name", Toast.LENGTH_SHORT).show();
        }
        else if ( ( !inputDesc.getText().toString().equals("")) )
        {
            Toast.makeText(getApplicationContext(),
                    "Please Enter Event Description", Toast.LENGTH_SHORT).show();
        }
        else if ( ( !inputCountry.getText().toString().equals("")) )
        {
            Toast.makeText(getApplicationContext(),
                    "Please Enter Place or Country", Toast.LENGTH_SHORT).show();
        }
        else if ( ( !inputdate.getText().toString().equals("")) )
        {
            Toast.makeText(getApplicationContext(),
                    "Please Select Date When Event Start", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(),
                    "Event Details are empty", Toast.LENGTH_SHORT).show();
        }


    }
});
}