0

I'm new here, I apologize if this is a lousy question to ask. But I'd like to know the difference between these two versions of code.

1) This one will allow the Toast to change instantaneously.

public Toast toast;
public void showToast(String text)
{
    if (toast != null)
    {
        toast.cancel();
    }
    toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
    toast.show();
}

2) This one doesn't change instantaneously.

public Toast toast;
public void showToast(String text)
{
    if (toast != null)
    {
        toast.cancel();
    }
    toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}

Why does it have to be Toast class.makeText and not toastObject.makeText? Or is it because show() method has to be separate? I'm still new to Java and Android, can someone explain what is the fundamental difference between the two? Thanks in advance.

Wong ZQ
  • 1
  • 1
  • 1
    fyi, the if will never be entered, i.e. 'toast' will always be null. It has been declared but not instantiated. – Al Lelopath Jul 19 '17 at 16:33
  • 1
    How will `toast != null` ever pass, its always going to be null. Also how is this not crashing your app because it should be – tyczj Jul 19 '17 at 16:33
  • `makeText()` is declared `static`, [see documentation](https://developer.android.com/reference/android/widget/Toast.html#makeText(android.content.Context, int, int), so it is not referenced by an instantiation of the class. – Al Lelopath Jul 19 '17 at 16:37
  • Oops thanks for pointing that out, the Toast declaration is actually global, already made changes – Wong ZQ Jul 19 '17 at 16:41
  • Possible duplicate of [Difference between Static methods and Instance methods](https://stackoverflow.com/questions/11993077/difference-between-static-methods-and-instance-methods) – Al Lelopath Jul 19 '17 at 16:48

2 Answers2

1

It is because makeText() comes from the Toast class which is imported as

import android.widget.Toast;  

So, it is a static method hence it needs to be called by the class name.

and

.show();

need not be seperate.

So,

toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();

will work.

Yash
  • 3,438
  • 2
  • 17
  • 33
0

Actually makeText() method of Toast class is a static method.

So, if we have to access a static method we have to call that method by ClassName.method().

Here, we are also doing in the Toast class as makeText() is a static method.

Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59