Toast message remain for long time - java

I want to show Toast when no results found after searching ,
I made a simple Toast but toast remains for long time and i want it to disappear after short time
this is code
public boolean onQueryTextSubmit(String query) {
final String[] dose = getResources().getStringArray(R.array.doses);
final String[] use = getResources().getStringArray(R.array.uses);
final String[] composition = getResources().getStringArray(R.array.composition);
final TypedArray img = getResources().obtainTypedArray(R.array.img);
for (String search : suggestions)
{
if (query.equals(search)){
for (int i =0; i<suggestions.length; i++){
if (query.equals(suggestions[i])){
Intent intent = new Intent(MainActivity.this,productDetails.class);
int im = img.getResourceId(i,-1);
intent.putExtra("img",im);
intent.putExtra("dose",dose[i]);
intent.putExtra("use",use[i]);
intent.putExtra("composition",composition[i]);
intent.putExtra("title",suggestions[i].toUpperCase());
startActivity(intent);
}
}
}
else if (query!= search){
Toast.makeText(MainActivity.this, "No Results Found", Toast.LENGTH_SHORT).show();
}
}
return false;
}

Your toast is showing in for loop, he is added to queue multiple time, remove it from loop

Related

Problem with obtaining consent with ump / admob / funding choices

Following this guide https://developers.google.com/admob/ump/android/quick-start I tried to add everything to my app.
What I did:
link funding choices to admob
added ump to build.gradle
added the app ID to android manifest
set up a dialog for the app in admob and activated it for the app
Then I added this code to my app
ConsentRequestParameters params = new ConsentRequestParameters
.Builder()
.setTagForUnderAgeOfConsent(false)
.build();
consentInformation = UserMessagingPlatform.getConsentInformation(this);
consentInformation.requestConsentInfoUpdate(
this,
params,
new ConsentInformation.OnConsentInfoUpdateSuccessListener() {
#Override
public void onConsentInfoUpdateSuccess() {
// The consent information state was updated.
// You are now ready to check if a form is available.
if (consentInformation.isConsentFormAvailable()) {
loadForm();
}
else {
Context context = getApplicationContext();
CharSequence toastText = "No Form Available";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
},
new ConsentInformation.OnConsentInfoUpdateFailureListener() {
#Override
public void onConsentInfoUpdateFailure(FormError formError) {
// Handle the error.
Context context = getApplicationContext();
CharSequence toastText = "Error";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
});
and
public void loadForm() {
UserMessagingPlatform.loadConsentForm(
this,
new UserMessagingPlatform.OnConsentFormLoadSuccessListener() {
#Override
public void onConsentFormLoadSuccess(ConsentForm consentForm) {
MainActivity.this.consentForm = consentForm;
if(consentInformation.getConsentStatus() == ConsentInformation.ConsentStatus.REQUIRED) {
consentForm.show(
MainActivity.this,
new ConsentForm.OnConsentFormDismissedListener() {
#Override
public void onConsentFormDismissed(#Nullable FormError formError) {
// Handle dismissal by reloading form.
loadForm();
}
});
}
}
},
new UserMessagingPlatform.OnConsentFormLoadFailureListener() {
#Override
public void onConsentFormLoadFailure(FormError formError) {
// Handle the error
}
}
);
}
However, I always end up getting the toast "Error" landing in onConsentInfoUpdateFailure(FormError formError) independet from testing on my mobile phone or in the virtual device (I am in europe btw).
Am I missing something?
Thanks,
Celdri
I had the same issue and I solved it just by configuring properly my adMob account.

Android with java

there is a snippet of code of an android app (Android Studio) in Java language I tried to understand,there is number 17 as an index of an array as I highlighted the line code in bold , I tried a lot but I couldn't understand what's that number, here is the snippet code
protected void onPostExecute(String result)
{
**if(result == "0")**
{
Context context = getApplicationContext();
CharSequence text = "Invalid IP address";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
char[] charArray = result.toCharArray();
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
**if(charArray[17]=='0')**
{
CharSequence text = "Invalid Password";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
_logged_in = false;
}
**if(charArray[17]=='1')**
{
CharSequence text = "You logged in successfully";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
_logged_in = true;
startActivity(intent);
}
}
Thanks in advance
Don't use
if(result == "0")
If you are working with a String you should use:
if(result.equals("0"))
Also
if(charArray[17]=='0')
means that charArray is an array and you are getting the element with index=17. Pay attention that the first index is 0.

Cancel an operation on Toast

I wrote a JSoup HTML scraping class for my Android project. This custom class puts the user-inputted zip code into the constructor, and would parse that HTML. It works in an asynchronous thread from my main thread. Since there is no right way to deal with incorrect zip codes, I had check for null in a particular element, specifically:
if(doc.select("div.columns").first().text() == null)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
If that particular element is null (meaning that no such data exists for this zip code), it would create a toast to the user. As to why try wouldn't work in this case, it is because JSoup and Java doesn't know whether the parse failed or not, since the web page still loads fine; only, there is no data, which would crash the app from a NullPointerException from the code following it.
Despite my Toast exception handling using .runOnUiThread, my app would still crash. Is there any particular methods that would cancel the operations that follow my null-checking method? I know I am crashing because Toast is not cancelling my operations, and is preceding to execute the following code which causes my NullPointerExceptions.
Posted is my full Pollen constructor.
public Pollen(int zipcode, final Context context)
{
this.context = context;
this.zipcode = zipcode;
Document doc;
try
{
// pass address to Wunderground's website using our inputted zipcode
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();
if(doc.select("div.columns").first().text() == null)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();
// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();
SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");
// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++)
{
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);
try
{
pollenMap.put(format.parse(dates.text()), levels.text());
}
catch (ParseException e)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
}
}
catch (IOException e)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
}
tl;dr I still want the Toast to show - but I want on-Toast, to cancel all operations that follow it, since I know that if this particular Toast shows, if the code following it executes, it would crash the app.
Since you already in a try-catch-block, can't you just throw an exception?
public Pollen(int zipcode, final Context context) {
this.context = context;
this.zipcode = zipcode;
Document doc;
try {
// pass address to Wunderground's website using our inputted zipcode
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();
if(doc.select("div.columns").first().text() == null) {
// Oh no! div.colums is empty. Lets throw an exception, which
// will prevent the code below from executing.
throw new IllegalStateException("div.columns is NULL");
}
// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();
// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();
SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");
// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++) {
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);
// Removed nested try-catch block
pollenMap.put(format.parse(dates.text()), levels.text());
}
} catch (IOException e) {
displayToast(context);
} catch (ParseException e) {
// We catch the ParseException here instead of nesting try-catch blocks.
displayToast(context);
} catch (IllegalStateException e) {
// Catch the IllegalStateException thrown when div.columns was null,
// and let the user know what went wrong.
displayToast(context);
}
}
private void displayToast(Context context) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
}
});
}

Using Toast to deal with exception outside of my Fragment class

Currently creating an Android app. I have a class called Pollen, on top of my Fragment class, and I am dealing with exception handling within this second class.
Here is my Pollen class.
public static class Pollen
{
#SuppressLint("SimpleDateFormat")
public Pollen(int zipcode, Context context)
{
this.context = context;
this.zipcode = zipcode;
Document doc;
try
{
// pass address to
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();
// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();
// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();
SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");
// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++)
{
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);
try
{
pollenMap.put(format.parse(dates.text()), levels.text());
}
catch (ParseException e)
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
}
}
catch (IOException e)
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
}
}
Since Pollen uses Network tasks, it's under an asynchronous thread which is irrelevant to this question.
Whenever Pollen is met under an exception, despite the Toast, the app would crash.
I was wondering - what is the accepted way to deal with exception on classes outside of the main class?
Your application is crashing because you are creating a toast from outsied the UI thread.
You cannot create a Toast from a class which is not running on the main thread(UI thread). But you can use the runOnUiThread (http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)) to execute code on the UI thread from your Pollen class.
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(YourActivity.this, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
}
});
For this to work you have to pass the Activity's context to you custom class and use the above method or you can throw exception and catch it from the activity and handle it there.

Is there a way to continuously update a method in an Android application?

I'm trying to create an app where you can enter in a series of button presses as a password. When you press the first button, a method would keep track of how much time has elapsed, and at 5 seconds, the button press data is stored.
long recordingTime = 0;
boolean isRecording = false;
// start timer for total recording time
if(!isRecording) {
isRecording = true;
recordingTime = System.currentTimeMillis();
}
public void update() {
long currentTime = 0;
// get current time
currentTime = System.currentTimeMillis();
// check if timer is over 5 seconds
if(currentTime - recordingTime >= 5000) {
isRecording = false;
Context context = getApplicationContext();
CharSequence text = "Max password time reached.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
There are a few ways to do this, but here's a straight-forward way to get it done:
view.postDelayed(new Runnable() {
#Override
public void run() {
//store data here
}
}, 5000);

Categories

Resources