How to set a string for Toast.makeToast(...) in android - android

In my class MainActivity I created a string:
String s = "Mystring";
And I want to do something like below:
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
Is it possible? If yes, how can I do it?

The documentation of Toast.makeText():
/**
* Make a standard toast that just contains a text view.
*
* #param context The context to use. Usually your Application or Activity object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG.
*/
public static Toast makeText (Context context, CharSequence text, int duration){ ... }
Notice the use of makeTEXT, not makeTOAST.
You mentioned you're working in an AsyncTask. It is not possible to create toasts from a non-UI thread. Make sure you're displaying your Toast either in onPreExecute, in onPostExecute, or in onProgressUpdate.

If you are using it inside an AsyncTask then write your code in onPostexecute() as you can't access it from doInBackground() since it's Non-UI thread.
Toast.makeText(YourActivityName.this, s, Toast.LENGTH_SHORT).show()

Ya that should work, wht is the problem you getting actually?
Try below code:
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();

String s="haha";
Context context = getApplicationContext();
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration).show();
//you are correct. just use charSequence equal to the string. it should work. works for me.

Related

Use custom method for getResources.getString(R.string.test) inside another method

First of all, I know separately how to make custom method to show Toast & show String which extend from resource.
See:
private void showToast(CharSequence text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
And for Extend String Resource:
private void setStringResource(int resource) {
getResources().getString(resource);
}
But, I want to use something like this:
showToast(setStringResource(R.string.please_check_connection));
And, it gives compiler error.
How can I do that? Please reply fast. Thank you.
When you are calling your setStringResource, you aren't returning any value. Modify your method to the following:
private String setStringResource(int resource) {
return getResources().getString(resource);
}
Now when you call this method when creating your Toast, the method returns a String.
Change your method to the following:
private void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private String setStringResource(int resource) {
return getResources().getString(resource);
}.

Why is my toast working with so many different contexts?

I'm working in my activity4.java and the code is:
public class Activity4 extends Activity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_4);
spinner=findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(Activity4.this==adapterView.getContext())
Toast.makeText(adapterView.getContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
I used adapterView.getContext() as context in the above code. But even if I replace it with getApplicationContext() like
Toast.makeText(getApplicationContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
or if I write getBaseContext() like this,
Toast.makeText(getBaseContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
The toast seems to work just fine. Why is it so?
This is the implementation of the makeText() method in Toast.java:
/**
* Make a standard toast that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application}
* or {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link #LENGTH_SHORT} or
* {#link #LENGTH_LONG}
*
*/
public static Toast makeText(Context context, CharSequence text, #Duration int duration) {
return makeText(context, null, text, duration);
}
As you can see in the comments for #param context explains that it usually is the application's context or the activity's context.
But the documentation:
This method takes three parameters: the application Context, the text
message, and the duration for the toast
states that the context must be the application Context.
Well it seems that Toast just needs a context.
If possible we must use application Context to avoid unexpected results.
Although I haven't seen any yet.

Call Method from one package to another

I am a beginner in this field.
How can i access a method from one package to another.
For example:
package add;
public class Addfunction {
int a,b,sum;
public int add(int x,int y)
{
a=x;
b=y;
sum=a+b;
return sum;
}
}
in my second package
package com.example.demoo;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int Result;
Addfunction addfunction=new Addfunction();
Result=addfunction.add(5, 10);
Toast.makeText(getApplicationContext(), Result , Toast.LENGTH_LONG).show();
}
}
while running it shows Unfortunately app is stop.
please help me to solve this.
There's nothing wrong in how you access the Addfunction class. But consider two things.
First, you must add an import for the Addfunction class before the MainActivity class definition:
import add.Addfunction;
although you probably already have that, because it wouldn't compile otherwise.
Second, you are probably using this makeText:
static Toast makeText(Context context, int resId, int duration)
Make a standard toast that just contains a text view with the text from a resource.
instead of this:
static Toast makeText(Context context, CharSequence text, int duration)
Make a standard toast that just contains a text view.
Note the second parameter is an int in the first case which refers to a resource. And you are just passing the result of your computation which is probably an invalid resource id.
You may want to try to build a message in a String object and pass it to makeText, like this:
String msg = "Result: " + Result;
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

How to prevent Multiple Toast Overlaps

I've been using a common "myToast" which I use "myToast.cancel() prior to issuing a new toast. For Android v2.3 and older, this works great. When a new toast needs to be sent, the old one, if still on-screen, is canceled (and disappears immediately) to be replaced with the new toast. This avoids stacking up a bunch of toasts if the user presses a key multiple times that needs the alert (and other conditions). My actual case is one toast appears when a wrong key is pressed, and another appears if the Clear key is not pressed.
For Android 4.0 and 4.1, issuing a myToast.cancel() before the next toast kills both the current and the next toast. The current cancel() API does indicate it cancels the current AND the next toast (which seems rather stupid). Why cancel a toast you want to put up?
Any ideas on making cancel work consistently across Android versions (and the way it works in v2.3 and older)?
I'll try some inelegant dual toast system with tracking for which toast is in use, but it seems such a pain work around this bad behavior in 4.x to get what works perfectly and logically in older Android versions.
Ok, I solved it, but it's not nearly as clean as I would have liked. I implemented a dual toast approach, where it alternates between two toasts. First we define the toasts for the activity prior to the OnCreate:
Toast toast0;
Toast toast1;
private static boolean lastToast0 = true;
In the OnCreate:
toast0 = new Toast(getApplicationContext());
toast0.cancel();
toast1 = new Toast(getApplicationContext());
toast1.cancel();
And finally, when I need to display the toast and cancel the prior toast at the same time I use something similar to:
if (lastToast0) {
toast0.cancel();
toast1.setDuration(Toast.LENGTH_LONG);
toast1.setText("new message");
toast1.show();
lastToast0 = false;
} else {
toast1.cancel();
toast0.setDuration(Toast.LENGTH_LONG);
toast0.setText("new message");
toast0.show();
lastToast0 = true;
}
If you need to just cancel an existing toast (before it times out) use:
toast0.cancel();
toast1.cancel();
Tested on Nexus 7 (4.1), Emulator 4.0, and several devices with Android 2.2, 2.3.
Instead of calling cancel(). Try resetting the text and call show(). This should cancel the last toast by itself
myToast.setText("wrong key")
myToast.show();
If you keep using the same myToast instead of creating one every time I guess they won't stack up.
Did nandeesh's solution not work for you?
His solution would be cleaner than using two different toasts.
For example, (expanding on his/her answer) prior to onCreate we'd declare the toast:
private Toast myToast;
and in onCreate we'd have to initialize it using makeToast (otherwise we'd get an error):
myToast = Toast.makeText(getApplicationContext(), null, Toast.LENGTH_SHORT);
and whenever we want a toast to be shown we'd simply call:
myToast.setText("some text");
myToast.show();
and this would replace the previous toast properly.
Here is my answer copied from another similar question here:
Android cancel Toast when exiting the app and when toast is being shown
The Boast class accomplishes exactly what you need.
The trick is to keep track of the last Toast that was shown, and to cancel that one.
What I have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.
When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).
Here's full code of the Boast wrapper I made - it mimics enough of the Toast methods for me to use it. By default the Boast will cancel the previous one, so you don't build up a queue of Toasts waiting to be displayed.
If you just want to know how to cancel the notifications when exiting your app, you will find lots of help in there.
package mobi.glowworm.lib.ui.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.lang.ref.WeakReference;
/**
* {#link Toast} decorator allowing for easy cancellation of notifications. Use this class if you
* want subsequent Toast notifications to overwrite current ones. </p>
* <p/>
* By default, a current {#link Boast} notification will be cancelled by a subsequent notification.
* This default behaviour can be changed by calling certain methods like {#link #show(boolean)}.
*/
public class Boast {
/**
* Keeps track of certain Boast notifications that may need to be cancelled. This functionality
* is only offered by some of the methods in this class.
* <p>
* Uses a {#link WeakReference} to avoid leaking the activity context used to show the original {#link Toast}.
*/
#Nullable
private volatile static WeakReference<Boast> weakBoast = null;
#Nullable
private static Boast getGlobalBoast() {
if (weakBoast == null) {
return null;
}
return weakBoast.get();
}
private static void setGlobalBoast(#Nullable Boast globalBoast) {
Boast.weakBoast = new WeakReference<>(globalBoast);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Internal reference to the {#link Toast} object that will be displayed.
*/
private Toast internalToast;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Private constructor creates a new {#link Boast} from a given {#link Toast}.
*
* #throws NullPointerException if the parameter is <code>null</code>.
*/
private Boast(Toast toast) {
// null check
if (toast == null) {
throw new NullPointerException("Boast.Boast(Toast) requires a non-null parameter.");
}
internalToast = toast;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Make a standard {#link Boast} that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, CharSequence text, int duration) {
return new Boast(Toast.makeText(context, text, duration));
}
/**
* Make a standard {#link Boast} that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
* #throws Resources.NotFoundException if the resource can't be found.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, int resId, int duration)
throws Resources.NotFoundException {
return new Boast(Toast.makeText(context, resId, duration));
}
/**
* Make a standard {#link Boast} that just contains a text view. Duration defaults to
* {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, CharSequence text) {
return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
}
/**
* Make a standard {#link Boast} that just contains a text view with the text from a resource.
* Duration defaults to {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #throws Resources.NotFoundException if the resource can't be found.
*/
#SuppressLint("ShowToast")
public static Boast makeText(Context context, int resId) throws Resources.NotFoundException {
return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Show a standard {#link Boast} that just contains a text view.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
*/
public static void showText(Context context, CharSequence text, int duration) {
Boast.makeText(context, text, duration).show();
}
/**
* Show a standard {#link Boast} that just contains a text view with the text from a resource.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #param duration How long to display the message. Either {#link Toast#LENGTH_SHORT} or
* {#link Toast#LENGTH_LONG}
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static void showText(Context context, int resId, int duration)
throws Resources.NotFoundException {
Boast.makeText(context, resId, duration).show();
}
/**
* Show a standard {#link Boast} that just contains a text view. Duration defaults to
* {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param text The text to show. Can be formatted text.
*/
public static void showText(Context context, CharSequence text) {
Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
/**
* Show a standard {#link Boast} that just contains a text view with the text from a resource.
* Duration defaults to {#link Toast#LENGTH_SHORT}.
*
* #param context The context to use. Usually your {#link android.app.Application} or
* {#link android.app.Activity} object.
* #param resId The resource id of the string resource to use. Can be formatted text.
* #throws Resources.NotFoundException if the resource can't be found.
*/
public static void showText(Context context, int resId) throws Resources.NotFoundException {
Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally
* have to call this. Normally view will disappear on its own after the appropriate duration.
*/
public void cancel() {
internalToast.cancel();
}
/**
* Show the view for the specified duration. By default, this method cancels any current
* notification to immediately display the new one. For conventional {#link Toast#show()}
* queueing behaviour, use method {#link #show(boolean)}.
*
* #see #show(boolean)
*/
public void show() {
show(true);
}
/**
* Show the view for the specified duration. This method can be used to cancel the current
* notification, or to queue up notifications.
*
* #param cancelCurrent <code>true</code> to cancel any current notification and replace it with this new
* one
* #see #show()
*/
public void show(boolean cancelCurrent) {
// cancel current
if (cancelCurrent) {
final Boast cachedGlobalBoast = getGlobalBoast();
if ((cachedGlobalBoast != null)) {
cachedGlobalBoast.cancel();
}
}
// save an instance of this current notification
setGlobalBoast(this);
internalToast.show();
}
}
Make a java class as ShowToast.java like below
public class ShowToast {
private static Toast toast;
public static void show(Context mcontext, String text) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(mcontext, text, Toast.LENGTH_SHORT);
toast.show();
}
}
Then call it as
ShowToast.show(getApplicationContext(),"YOUR_TOAST_TEXT");
cancel() doesn't do anything I'm afraid.
I would suggest using Crouton https://github.com/keyboardsurfer/Crouton
This my solution works perfect both for 4.* and 2.3 Android versions
static Toast toast;
.....
if (toast != null)
toast.cancel();
boolean condition = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
if ((toast == null && condition) || !condition)
toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
if ((toast != null && condition))
toast.setText(text);
toast.show();
Create an Toast Object:
Toast toastobject=null;
Now use the below code to display the toast. This will work find for me
int index = clickCounter-1;
if(toastobject!= null)
{
toastobject.cancel();
}
toastobject = Toast.makeText(this,"Toast Text" , Toast.LENGTH_SHORT);
listItems.remove(index);
toastobject.show();
create new function and call this.
ImageButton ABtn = (ImageButton) findViewById(R.id.Btn);
ABtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
SETToast("mytext");
}
});
private Toast toast = null;
public void SETToast( String text)
{
if(toast==null)
{
toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast=null;
}
}, 2000);
}
else
{
toast.setText(text);
}
}
Kotlin approach:
class MyActivity: Activity {
private var toast: Toast? = null
fun yourFunction() {
toast?.cancel()
toast = if(documentWasSaved) {
makeText(this, "Document was saved"), Toast.LENGTH_LONG)
} else {
makeText(this, "Failed to save your document", Toast.LENGTH_LONG)
}
toast?.show()
}
}

Why Toast.makeText and not new Toast

This is may be a noob question, but I was wondering why do we have to use a static method (makeText) to create a Toast and not a constructor.
Why do we have to use this:
makeText(Context context, CharSequence text, int duration)
instead of this:
new Toast(Context context, CharSequence text, int duration)
This is the makeText method:
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
Why don't we have the following:
public Toast (Context context, CharSequence text, int duration) {
this(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
this.mNextView = v;
this.mDuration = duration;
}
I searched the web and source code for any reason but I didn't find.
Please if you have an idea, don't hesitate.
The question basically drill downs to when should I make a method static. The answer is simple- when your method has a very specific task and does not change the state of the object.
Something like a utility method, say add(int a, int b) which simply returns a+b. If I need to store the value a+b for later use for the object, static method is strictly no-no (you will not be able to store a non static variable in a static method). But if we are dealing with some action which is independent of state of the object, static is the answer.
Why are we giving preference to static if it is independent of state of object?
Memory- static method will only have one copy, irrespective of the actual number of object.
Availability- Method is available even if you don't have single object
Ofcourse the downside is that we are keeping a copy of method even if we do not use it at all (if it was non-static and no object was created, we would have saved this space). But this is of lower weight than the advantages mentioned above.
As the method we are discussing here (makeText), does not need to maintain a state for later use, the best way to go is static method.
--Edit--
The answer mentioned above is more generic as to when we should use static and when non-static, let me get specific to Toast class.
Toast class gives us 2 ways to create a Toast object (Refer http://developer.android.com/reference/android/widget/Toast.html)
makeText(Context context, CharSequence text, int duration) which returns a Toast object which the values assigned.
Normal way, use new Toast(context) to create an object, then set values as required.
If you use method 1, you are saying something like Toast.makeText(context, text, duration).show(); and we are done. I use this method all the time.
Method 2 is used only for a specific case, from http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Do not use the public constructor for a Toast unless you are going to
define the layout with setView(View). If you do not have a custom
layout to use, you must use makeText(Context, int, int) to create the
Toast.
#CFlex, If I got your question properly, I guess you just want to know why we have Toast.makeText(context, text, duration) returning a Toast object, when the same thing could have been done by a constructor.
Whenever I look at something like ClassName.getObject returning object of class, I think about singleton pattern. Well, in this case we are not exactly talking about singleton, I would like to assume that makeText returns same object always (to save creation of N objects), otherwise it is just a fancy thing developed by Android team.
One rule: Ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
Remember that objects live in memory and they are created for certain jobs. Static methods are available for all the objects in a class and it is not necessary to create an object to use them.
So there is no reason to create an object Toast to be able to access the method makeText, when you can access it as a static method (more elegant and compact)
As far as I know:
That's because we don't wish to hold an instance of the object toast, which would require an amount of memory persistently used until cleaned by the GarbageCollector.
And that it always have access to being displayed, so it is not required by your application to have any set of permissions.

Categories

Resources