Search code examples
androidandroid-studiotoast

Why does Toast.makeText is not accepting formatted text?


Being a begginer in android , i have been stuck while using Toast.makeText ,here is the code.

public class CustomOnSelectedListen implements OnItemSelectedListener{

public void onItemSelected(AdapterView<?> parent, View view,int pos,long id){
    Toast.makeText(parent.getContext(),
            "OnItemSelectedListener :" + parent.getItemAtPosition(pos).toString(),
            Toast.LENGTH_SHORT).show();
}

 public void onNothingSelected(AdapterView<?> arg0){
     Toast.makeText(CustomOnSelectedListen.this,"Please select place and class".toString(),Toast.LENGTH_SHORT).show();
 }

}

and the error is

Error:(19, 15) error: no suitable method found for  
       makeText(CustomOnSelectedListen,String,int)
method Toast.makeText(Context,CharSequence,int) is not applicable
(argument mismatch; CustomOnSelectedListen cannot be converted to Context)
method Toast.makeText(Context,int,int) is not applicable
(argument mismatch; CustomOnSelectedListen cannot be converted to Context)

Here CustomOnSelectedListen cannot be converted, what might be wrong?

EDIT 1: Yes CustomOnSelectedListen was not an context instance , i need to display a message in the function onNothingSelected() using toast,what are the different ways to do it?


Solution

  • On your onNothingSelected function:

    Toast.makeText(CustomOnSelectedListen.this,"Please select place and class".toString(),Toast.LENGTH_SHORT).show();
    

    First parameter (CustomOnSelectedListen.this) is not a Context instance.