Why is no data sent to the database? [duplicate] - java

I have an activity with a button, when the user clicks on the button, an AlertDialog appear with 2 EditText where you put email and password to login.
When I try to get the text from the EditText i always get only empty strings.
The layout login_alert is the layout of the AlertDialog.
Here the code:
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
String email = ((EditText) view.findViewById(R.id.emailEditText)).getText().toString();
String password = ((EditText) view.findViewById(R.id.passwordEditText)).getText().toString();
System.out.println("DEBUG: "+email+", "+password); // Empty strings
EDIT:
Activity code:
public class MainActivity extends FragmentActivity {
public static final String mAPP_ID = "...";
public static final String USER_DB_URL = "...";
AssetsExtracter mTask;
private MainFragment mainFragment;
private List<User> usersList = new ArrayList<User>();
private User currentUser = null;
private Button labLoginButton;
private EditText emailET;
private EditText passwordET;
private ProgressDialog dialog;
private View alertView; /* THIS IS THE SOLUTION */
boolean userIsLogged = false;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
/*View view = getLayoutInflater().inflate(R.layout.login_alert, null, false); BEFORE*/
alertView = getLayoutInflater().inflate(R.layout.login_alert, null, false);
emailET = (EditText) view.findViewById(R.id.emailEditText);
passwordET = (EditText) view.findViewById(R.id.passwordEditText);
labLoginButton = (Button) findViewById(R.id.loginLabButton);
updateLoginButton();
dialog = new ProgressDialog(this);
dialog.setMessage("Signin in...");
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mTask = new AssetsExtracter();
mTask.execute(0);
}
/* THIS METHOD IS CALLED BY THE LOGIN BUTTON IN THE MAIN ACTIVITY LAYOUT */
public void onLabLoginButtonClick(View v) {
if (userIsLogged) {
currentUser = null;
userIsLogged = false;
updateLoginButton();
Toast.makeText(this, "Disconnected from Lab", Toast.LENGTH_SHORT)
.show();
} else {
/*View messageView = getLayoutInflater().inflate(
R.layout.login_alert, null, false); BEFORE */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon_launcher);
builder.setTitle(R.string.login_string);
builder.setView(alertView); /* USING THE GLOBAL VARIABLE */
builder.setPositiveButton("Sign me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog.show();
// Download user and return a List of User
DownloadFilesAsyncTask task = new DownloadFilesAsyncTask(USER_DB_URL) {
#Override
protected void onPostExecute(final List<User> result) {
usersList = result;
loginCheckRoutine(); //HERE I MANAGE THE LOGIN AND GETTING EMPTY STRING
}
};
task.execute();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create();
builder.show();
}
}
public void updateLoginButton() {
if (userIsLogged) {
labLoginButton.setText(R.string.logout_string);
} else {
labLoginButton.setText(R.string.login_string);
}
}
public void loginCheckRoutine() {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
System.out.println("DEBUG: " + email + ", " + password); // EMPTY
// controllo nella lista se c'è l'utente coi dati inseriti
for (int i = 0; i < usersList.size(); i++) {
if (usersList.get(i).getEmail().equals(email)
&& password.equals("admin")) {
currentUser = usersList.get(i);
userIsLogged = true;
updateLoginButton();
dialog.dismiss();
break;
}
}
if (!userIsLogged) {
userIsLogged = false;
updateLoginButton();
dialog.dismiss();
Toast.makeText(MainActivity.this, "Login Failed",
Toast.LENGTH_SHORT).show();
}
}
}
PROBLEM SOLVED, SOLUTION:
In the onCreate() I inflate the alert_dialog layout in a View variable. I made that View variable global (before onCreate()) and then in onLabLoginButtonClick() I don't inflate the view again, but I use that global instantiated in the onCreate(). hope its clear. thank you all!

You getText just after initialization. Untill you have text in xml you won't get the text. In onclick of alertdialog button get the text.
Declare
EdiText ed1,ed2; // before onCreate if in activity and onCraeteView in fragment
as a instance variable
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
ed1= (EditText) view.findViewById(R.id.emailEditText))
ed2 = (EditText) view.findViewById(R.id.emailEditText);
then on Alert dialog Button click
String email = ed1.getText().toString();
String password= ed2.getText().toString()

you must get the text when you click on login button of alert dialog box
the above mentioned code you get text when you show alert dialog it always return always empty string you should follow the following procedure
first you make a custom alert box layout having two edit text and one button
user write text to edittext for login and give password and then click login button
when you call login button click listener you can get text of edittext easyly

You are trying to get the text immediately after you inflated the view. Try doing it when the user clicks the done button instead.

Before onCreate add:
EditText email;
EditText pass;
Add this in your onCreate
etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);
Then add this to when your button is clicked
String email = etEmail.getText().toString();
String pass = etEmail.getText().toString();

Just ensure that the editText.getText.toString() method is inside the OnClick() method, eg:
TextView submit = enquiryFragment.findViewById(R.id.query_submit_button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
query_type = query_type_editText.getText().toString();
query_text = query_editText.getText().toString();
if (query_text.length()!=0 && query_type.length()!=0) {
postQuery(query_type, query_text, store_id);
// Log.e("query_type ",query_type );
}else{
Toast.makeText(getContext(), "Enter something !", Toast.LENGTH_SHORT).show();
}
}
});

Alternatively add a TextChangedListener to you textview to change the change the string every time the textboxtext changes.
A textwatcher is also possible

you should get the text when you click on save or done button.
If you get this text on click of alert dialog button, you may end up taking it multiple times.

Related

I am building an attendance app and I face this error 'void android.app.Dialog.setOwnerActivity(android.app.Activity)' How can I overcome this?

My Dialog class shows error and I don't know what happens with my code where it generate error I check multiple times and still not get a solution.
Please Help to get rid of this....
public class MyDialog extends DialogFragment {
public static final String CLASS_ADD_DIALOG = "addClass";
public static final String STUDENT_ADD_DIALOG = "addStudent";
OnClickListener listener;
public interface OnClickListener {
void onClick(String text1, String text2);
}
public void setListener(OnClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog =null;
if(getTag().equals(CLASS_ADD_DIALOG))dialog = getAddClassDialog();
//Here android studio shows an error
if(getTag().equals(STUDENT_ADD_DIALOG))dialog = getAddStudentDialog()
return dialog;
}
private Dialog getAddStudentDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog, null);
builder.setView(view);
TextView title = view.findViewById(R.id.titleDialog);
title.setText("ADD NEW STUDENT");
EditText roll_edt = view.findViewById(R.id.roll);
EditText name_edt = view.findViewById(R.id.name);
// And also here it shows error
roll_edt.setHint("Roll");
name_edt.setHint("Name");
Button cancel = view.findViewById(R.id.cancel_btn);
Button add = view.findViewById(R.id.add_btn);
cancel.setOnClickListener(v -> dismiss());
add.setOnClickListener(v -> {
String roll = roll_edt.getText().toString();
String name = name_edt.getText().toString();
roll_edt.setText(String.valueOf(Integer.parseInt(roll)+1));
listener.onClick(roll, name);
});
return builder.create();
}
private Dialog getAddClassDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog, null);
builder.setView(view);
TextView title = view.findViewById(R.id.titleDialog);
title.setText("ADD NEW CLASS");
EditText class_edt = view.findViewById(R.id.edt01);
EditText sub_edt = view.findViewById(R.id.edt02);
class_edt.setHint("Class");
sub_edt.setHint("Sub");
Button cancel = view.findViewById(R.id.cancel_btn);
Button add = view.findViewById(R.id.add_btn);
cancel.setOnClickListener(v -> dismiss());
add.setOnClickListener(v -> {
String className = class_edt.getText().toString();
String subName = sub_edt.getText().toString();
listener.onClick(className, subName);
dismiss();
});
return builder.create();
Rather than this it shows multiple error without blue lines shows error of Fragment.
enter image description here

How to create a second spinner whose list of options depends on the input of the first spinner?

I've searched the web and couldn't find a solution.
What I'm trying to do is display a list of an array on the second spinner depending on the selected option from the first spinner.
The logic would be something like this:
If the First spinner = CSE/IT
Then Second Spinner Options would be:
1. BCA 2. MCA
Here's my java code:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener
{
private EditText TextFname;
private EditText TextMname;
private EditText TextLname;
//private EditText TextDept;
private Spinner SpinDept;
private Spinner SpinProg;
//private EditText TextProg;
private EditText TextSemester;
private EditText TextRolln;
private EditText TextEmail;
private EditText TextPassword;
private EditText TextPasswordConfirm;
//private FirebaseFirestore db = FirebaseFirestore.getInstance();
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
private ProgressBar pBar;
private View bgBlur;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
TextFname = findViewById(R.id.Fname);
TextMname = findViewById(R.id.Mname);
TextLname = findViewById(R.id.Lname);
//TextDept = findViewById(R.id.Dept);
SpinDept = findViewById(R.id.Dept);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.department_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinProg = findViewById(R.id.Prog);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
R.array.programme_array, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//TextProg = findViewById(R.id.Prog);
TextSemester = findViewById(R.id.Semester);
TextRolln = findViewById(R.id.Rolln);
TextEmail = findViewById(R.id.Email);
TextPassword = findViewById(R.id.Password);
TextPasswordConfirm = findViewById(R.id.PasswordConfirm);
findViewById(R.id.SubmitButton).setOnClickListener(this);
pBar=findViewById(R.id.indeterminateBar);
bgBlur=findViewById(R.id.bgblur);
}
//Validation method
private boolean validate()
{
AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
mAwesomeValidation.addValidation(TextFname, "\\D+", "Invalid First Name");
mAwesomeValidation.addValidation(TextLname, "\\D+", "Invalid Last Name");
//mAwesomeValidation.addValidation(TextDept, "\\D+", "Invalid Department Name");
//mAwesomeValidation.addValidation(TextProg, "\\D+", "Invalid Programme Name");
mAwesomeValidation.addValidation(TextSemester, "[1-9]+[0-9]{0,}", "Invalid Semester (Cannot be less than 0)");
mAwesomeValidation.addValidation(TextRolln, "[a-zA-Z-0-9\\s]+", "Invalid Roll Number");
mAwesomeValidation.addValidation(TextEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!##\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{6,}";
mAwesomeValidation.addValidation(TextPassword, regexPassword, "Use 6 or more characters with a mix of upper & lower letters, numbers & symbols");
mAwesomeValidation.addValidation(TextPasswordConfirm, TextPassword, "Password does not match");
return mAwesomeValidation.validate();
}
#Override
public void onClick(View v)
{
// Check for particular button click, because this method will be called for every
// click on any view on which onClickListener is set as setOnClickListener(this).
// In this case currently it doesn't matter as there is only one button, but in case
// if you also add for example clear field button, then you need to know which
// button was clicked.
switch (v.getId())
{
case R.id.SubmitButton:
if (validate())
{
String TextDept = SpinDept.getSelectedItem().toString();
String TextProg = SpinProg.getSelectedItem().toString();
pBar.setVisibility(View.VISIBLE);
bgBlur.setVisibility(View.VISIBLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
//Toast.makeText(this, "Validation successful", Toast.LENGTH_SHORT).show();
/*String Firstname = getTrimmedInput(TextFname);
String Middlename = getTrimmedInput(TextMname);
String Lastname = getTrimmedInput(TextLname);
String Department = getTrimmedInput(TextDept);
String Programme = getTrimmedInput(TextProg);
String Semester = getTrimmedInput(TextSemester);
String Rollnumber = getTrimmedInput(TextRolln);
String Password = getTrimmedInput(TextPassword);*/
String Email = getTrimmedInput(TextEmail);
final CollectionReference dbUsers = db.collection("Students");
final DocumentReference dbDocs = dbUsers.document(Email);
//Student student = new Student(Firstname, Middlename, Lastname, Department, Programme, Integer.parseInt(Semester), Rollnumber, Email, Password);
//Alternative way how to create data model. I think builder pattern is easier
// to operate as you don't have to know in which order you should pass variables
// (especially when you have a lot of them) to model constructor.
// Although I don't know if my class would work as I don't know how your
// DB backend requests data from your student class as in my model some
// getter method name cases are different. Currently I created my Student
// model as example and it's not used.
final StudentImproved studentImproved = new StudentImproved.Builder()
.setFirstName(getTrimmedInput(TextFname))
.setMiddleName(getTrimmedInput(TextMname))
.setLastName(getTrimmedInput(TextLname))
.setDepartment(TextDept)
.setProgramme(TextProg)
.setSemester(Integer.parseInt(getTrimmedInput(TextSemester)))
.setRollNumber(getTrimmedInput(TextRolln))
.setEmail(getTrimmedInput(TextEmail))
.setPassword(getTrimmedInput(TextPassword))
//.setPasswordConfirm(getTrimmedInput(TextPasswordConfirm))
.build();
dbUsers.document(Email)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
{
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task)
{
if (task.isSuccessful())
{
if (task.getResult().exists())
{
pBar.setVisibility(View.GONE);
bgBlur.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(RegisterActivity.this, "You already have your data stored in the database", Toast.LENGTH_LONG).show();
}
else
{
dbDocs.set(studentImproved)
.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
pBar.setVisibility(View.GONE);
bgBlur.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(RegisterActivity.this, "Successfully Registered",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
pBar.setVisibility(View.GONE);
bgBlur.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
});
}
/*else
{
Toast.makeText(this, "Validation failed", Toast.LENGTH_LONG).show();
}
break;*/
}
}
private String getTrimmedInput(EditText text)
{
return text.getText().toString().trim();
}
}
Here's my Spinner XML code:
<Spinner
android:id="#+id/Dept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="131dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="132dp"
android:entries="#array/department_array"
android:spinnerMode="dropdown"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Rolln" />
<Spinner
android:id="#+id/Prog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="179dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="180dp"
android:entries="#array/programme_array"
android:spinnerMode="dropdown"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Dept" />
Here's my String XML Code:
<string-array name="department_array">
<item>Civil</item>
<item>CSE/IT</item>
<item>Electronics</item>
</string-array>
<string-array name="programme_array">
<item>B.Tech Civil</item>
<item>BCA</item>
<item>MCA</item>
</string-array>
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// load spinner2 data from database method loadData
List<String> spinner2Data= helper.loadData(spinner1.getSelectedItem().toString());
// Create adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(CurrentActivity.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,spinner2Data);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
In the first spinner's setOnItemSelectedListener Load the second spinner based on the ID match or name of department. As you asked where to put setOnItemSelectedListener it should be inside onCreate method the very first method of your activity. For this you can use model classes.
SpinProg = findViewById(R.id.Prog);
SpinDept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
programmeArray.clear();
// Here put your logic for selecting programs against each department and initialize programmeArray then load progSpinner with that array
/*
* for(int i=0; i<totalPrograms.size; i++){
*
*
*if(totalPrograms.get(i).getName.equals(totalDepartments.get(position).getName)){
* programmeArray.add(totalPrograms.get(i));
* }
* }
* */
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
programmeArray, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) { }
});

Passing dialog selected items to other activities or adapters

I am have struggling with trying to add a feature on my project and I need some help on how I can move beyond this step. So I have decided to create a method selectCurrency() on my preferencesFragment class As you can see I have created a simple Dialog with not more than 6 currencies, what I want to do is once a currency is selected from this dialog I want to display it on my currency adapter.
public class PreferencesFragment extends PreferenceFragment {
final static String[] items = {"$ - US Dollar", "€ - Euro", "£ - British Pound","IRN - IRN ","A$ - Australian Dollar", " CA$ - Canadian Dollar"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from the XML resource
addPreferencesFromResource(R.xml.pref_general);
//show currency
final Preference currencyPreference = findPreference
(getResources().getString(R.string.setting_category_currency_change_button_key));
currencyPreference.setOnPreferenceClickListener(preference -> {
selectCurrency();
return false;
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void selectCurrency() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Currency")
.setItems(items, (dialog, which) -> {
// String selectedText = items[which].toString();
Toast.makeText(getActivity(), items[which] + " was selected", Toast.LENGTH_SHORT).show();
});
builder.setPositiveButton("OK", null);
builder.setNegativeButton("CANCEL", null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
button.setBackgroundColor(Color.argb(100,100,25,51));
button.setTextColor(Color.WHITE);
}
}
Here is my adapter.
So currently I am using a string which is not right, so how can I get the selected currency from the above fragment to my adapter down here: at holder1.setWalletAmountView("$ " + Double.valueOf(walletBalance).toString());
public class CurrencyAdapter extends RecyclerView.Adapter<CurrencyAdapter.GeneralViewHolder> {
#Override
public void onBindViewHolder(GeneralViewHolder holder, int position) {
if (getItemViewType(position) == -1) {
MonthSummaryCard holder1 = (MonthSummaryCard) holder;
holder1.setWalletAmountView("$ " + Double.valueOf(walletBalance).toString());
holder1.setTotalExpensesPerMonth("$ " + Double.valueOf(totalExpenseAmount).toString());

How Can I put a error msg if there is a blank field on Java?

I am trying to make a unit converter and it seems its working i just need to give them an error if they don't put any number on the first field and other error if they put a number on the second field (so they cant convert it backwards)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
Button buttonConvert = (Button)findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
}
});
}
}
You can use Toast to give a error message.
But I use EditText.setError() method. So user will be able see exactly which field is responsible for validation problem
Click HERE for a tutorial and Here for another solid tutorial.
This is a sample code (I do not have ADT in here, so forgive me if it needs some correction):
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
#Override
public void onClick(View arg0) {
boolean isValid = true;
if (editCentimeters.getText().toString().isEmpty())
{
editCentimeters.setError("This input cannot be null");
isValid = false;
}
if (editInches.getText().toString().isEmpty())
{
editInches.setError("This input cannot be null");
isValid = false;
}
if (isValid)
{
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
}
}
use setError() method for this. do somthing like this
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(editCentimeters.getText().toString().equals("")){
editCentimeters.setError("*Field Required");
}else{
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
}
}
});
The Toast class will be suitable for this purpose as:-
if(editText.getText().toString().equals(""))
Toast.makeText(this,"Your Error msg",Toast.LENGTH_LONG).show();
The first argument is the Context of your Activity
Second is the CharSequence
And third is the duration of the Toast.
You must check the value inside each EditText yourself, and notify the user if its empty:
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(!"".equals(editCentimeters.getText().toString())) {
// If the field is not empty, proceed to calculation
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
} else {
// If it's empty, show a message to the user)
editCentimeters.setError("This field can not be empty");
}
}
};
editinches should b a textview so that user can't edit or add any value... Next use should do a check if editcentimeter is empty, if yes you display an error... Can be Alertdialog, toast to show the error message.
if(editcentimeter.isEmpty(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Missing value");
// set dialog message
alertDialogBuilder
.setMessage("Please enter a value");
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Please enter a numbert!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dismiss();
}
});
}
}

Android Text validation

Hi I am creating a task reminder app. It works but I would like to create some sort of Toast validation. For example a user doesn't fill in the title and I'd like an toast saying "title needs to be filled in!" e.t.c
But I'm not sure how to do this.
I am using an EditText widget by the way.
This is one method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
registerButtonListenersAndSetDefaultText();
}
and another:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == null) {
long id = mDbHelper.createReminder(title, body, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
Thanks.
You should check inside your submit button's click listener whether all the necessary fields are filled in properly, and if not, just show up the toast:
Toast.makeText(getApplicationContext(), "Title needs to be filled in!",
Toast.LENGTH_SHORT).show();

Categories