Toast messages being queued? - android

When my submit button is clicked, it calls a method which checks if a certain EditText is empty and displays a toast message as an error message accordingly. However, if I rapidly tap on submit, it "queues" a lot of toast messages. How can I prevent this?
Here's my method:
private void checkName() {
if (etName.getText().toString().isEmpty()) {
Toast toast = Toast.makeText(this, "Please enter your name", Toast.LENGTH_LONG);
toast.show();
} else {
submit();
}
}

What happens is you are creating new toasts each time checkName() is called, hence they are "queued" by the system and shown one after another. You can try the following to ensure you are just making one toast and simply show it when needed:
Toast mToast;
private void checkName() {
if (etName.getText().toString().isEmpty()) {
if (mToast == null) { // Initialize toast if needed
mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
}
mToast.setText("Please enter your name"); // Simply set the text of the toast
mToast.show(); // Show it, or just refresh the duration if it's already shown
} else {
submit();
}
}

Related

validate editText on buttonclick event [duplicate]

This question already has answers here:
Form validation on Button click in android
(3 answers)
Closed 5 years ago.
I am new in android programming and still learning. for practice i started to create a very simple and basic app which calculate age on button click which take birth year as an input.
i manage to get it working and want to do some validation on it. like i have done validating that the value we provide should not be more than current year and i successfully done that.
Now my problem is that i also want to put validation that if no input is been made and button is pressed then it should alert the user by Toast. So far i have tried doing but every time i press button without anything in editText the app just crash.
here's my code.
calcAge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(dob > year){
Toast.makeText(getApplicationContext(), "Provide valid Input", Toast.LENGTH_SHORT).show();
}
else if(String.valueOf(dob) == null){
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
}
else{
dob = Integer.parseInt(String.valueOf(inAge.getText()));
currentYear.setText("Your Curret Year is :- " + year);
yourYear.setText("Your Birth Year is :- "+ dob);
int a = year-dob;
finalAns.setText("Your Age is :- " + a);
inAge.setText("");
}
}
});
above code is of button click. Please provide with some solution
I have also tried putting editText1.getText().toString.trim().lenght()==0 in if condition but that also didn't worked and app just crashes.
try this on button click listner
calcAge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (yourEdittext.getText().toString().equals("")) {
yourEdittext.setError(getString("filed can't be empty"));
yourEdittext.requestFocus();
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
}
}
});
Use this:
String dob = yourEditText.getText().toString();
then check it like this:
if (TextUtils.isEmpty(dob)) {
//show toast
}
You have to do validation like this :
doneDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validationDetails()){
//If get all data do Action
}else{
// Toast.makeText(getApplicationContext(),"Field Missing",Toast.LENGTH_SHORT).show();
}
}
This is the validation part method:
private boolean validationDetails() {
if (userNameET.getText().toString().isEmpty()) {
userNameET.setError("Enter Patient Name");
return false;
}
if (ageET.getText().toString().isEmpty()) {
ageET.setError("Enter Age ");
return false;
}
if (gender.getSelectedItem().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Select Gender",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
On button click, you are checking first if dob is greater than a year. which is not correct. First, check if dob is null or empty. then check for if greater than year
If (dob == null && dob.isEmplty){
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
} else if(dob > year){
Toast.makeText(getApplicationContext(), "Provide valid Input", Toast.LENGTH_SHORT).show();
} else {
//do what ever you want
}
try this on your button click :
if ( yourEditText.getText().toString().equal("")) {
Toast.makeText(getApplicationContext(), "Please Give Some Input", Toast.LENGTH_SHORT).show();
}

how to add counter in android studio to quit an application

I am getting an error when I set the counter to subtract and close the application. I get an error "cannot assign value to final variable counter". If the user logins in 3 times with no success quit the application.
final int counter = 3;
//Set the OKButton to accept onClick
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
//display text that was inputed for userText and passText
user = userText.getText().toString();
pass = passText.getText().toString();
//create if loop which checks if user and pass equals the credentials
if (user.equals("pshivam") && pass.equals("Bway.857661")) {
//display toast access welcome
String welcome = "Access Granted.";
//Create a Toast to display the welcome string in the MainActivity.
Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show();
setContentView(R.layout.account_main);
}
//create else if loop which checks if user or pass does not equals the credentials
else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){
//displays previous entry
userText.setText(user);
passText.setText(pass);
//allows user to re-enter credentials.
user = userText.getText().toString();
pass = passText.getText().toString();
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
}
});
}
}
Do something like this :
OKButton.setOnClickListener(new View.OnClickListener() {
int counter = 3;
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
You can also call a function from inside onClick which will decrement the variable, or use a static field declared in your class
This How to increment a Counter inside an OnClick View Event and How do I use onClickListener to count the number of times a button is pressed? might help.
Edit:
What you are doing in else part doesn't make sense. You are setting text for userText and passText that you just got using getText() from these. Then you are storing these same values to user and pass. But you aren't using these variables anywhere and they get new values when onClick is called again. Why not keep it simple :
else {
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}

'No network' Toast not displayed in onCreate

Hello everyone i hope you can help.
I've built an RSS reader which populates a ListView. I want to check the user has network access on app start up, if there is no network then the user should see the setEmptyView View and a toast.
In onCreate I've set the list adapter with an empty list so I'm expecting to see the empty view. Then i query the network state and if no network i create a toast. BUT I never see the empty view on start-up and i never see the toast when i don't have a network. Whats going on?
public class XMLActivity extends ListActivity {
private List<JSONObject> jobs = new ArrayList<JSONObject>();
private RssListAdapter adapter;
private ListView lv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//SET LAYOUT WITH EMPTY LIST VIEW
setContentView(R.layout.main);
View empty = findViewById(R.id.empty);
lv = getListView(); //get view layout
lv.setEmptyView(empty); //set empty view
adapter = new RssListAdapter(this,jobs); //jobs is empty array list
setListAdapter(adapter);
//CHECK FOR NETWORK AND DISPLAY TOAST
try{
boolean network = RssReader.isOnline(this); //check network state
if (!network){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
// START RSS READER HANDLER
try {
jobs = RssReader.getLatestRssFeed();
} catch (Exception e) {
}
//REFRESH ADAPTER FOR LISTVIEW
adapter.clear();
for(JSONObject job :jobs){
adapter.add(job);
}
adapter.notifyDataSetChanged();
lv.setClickable(true);
Why can't i see the empty view or toast, this problem only happens for the onCreate routine. Later toasts and empty views are displayed fine on menu item select so it seems to be a problem specific to the onCreate sequence.
try Toast.makeToast(this, "msg to user", Toast.TOAST_MSG_SHORT).show(); i'm sure i have a typo in there as i don't have my devopment machine up and running (yet).
use :
Toast.makeText(XMLActivity.this , "No Network", Toast.LENGTH_LONG).show();
if (!network){
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
TextView txt1 = new TextView(this);
txt1.setText("No Network");
toast.setView(txt1);
toast.show();
}
else ...
Try this..,,.
You have one condition not covered - what happens if network == true?
try{
boolean network = RssReader.isOnline(this); //check network state
if (!network){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(XMLActivity.this, "Network Access!", Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}

Using a != statement with an edittext object in java?

Im trying to create a button which when pushed reads the edittext box to
Make sure its not blank
Make sure its not the default text in this case "First Name".
However when the button is pushed it still preforms the action even if the edittext text is First Name or blank. Is there an easier way to do this? Also the toast are not made when the text is First Name or blank.
createp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (fname.getText().toString() != "")
if (fname.getText().toString() != "First Name"){
prefsEditor.putInt("user", 1);
prefsEditor.commit();
}
if (fname.getText().toString() == "")
{
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
if (fname.getText().toString() == "First Name") {
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
}});
}
Try this instead:
if (!fname.getText().toString().equals(""))
...
Another example:
if (fname.getText().toString().equals("First Name"))
....

how to check if the toast have dismissed or not [duplicate]

This question already has answers here:
Stop all toast messages when going to another screen in Android
(3 answers)
Closed 8 years ago.
i want to check if the toast have dismissed or not ,because user click the mouse the toast is show,but may me the user continuous click,so i need to check,i cannot use the dialog
Toast toast = null;
if (toast == null || toast.getView().getWindowVisibility() != View.VISIBLE) {
toast = Toast.makeText(getApplicationContext(),
"Text", Toast.LENGTH_SHORT);
toast.show();
}
Check if the toast is visible before you show it again.
Toast toast = yourToastCreationCode();
if (null == toast.getView().getWindowToken())
{
yeahToastIsInvisible();
}
Based on Denis answer, but worked better for me.
Toast t;
t=Toast.makeText(getActivity(), "test", Toast.LENGTH_LONG);
t.show;
if (t.getView().isShown())
{
//visible
}

Categories

Resources