Click here to Skip to main content
15,910,211 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got this error when i inserted MainActivity as a Parameter in Toast. This is the code

public class Toaster implements OnClickListener {

@Override
public void onClick(View clickedButton) {

String greetingText = "Hello from Android!";

Toast tempMessage = Toast.makeText(MainActivity.this , greetingText, Toast.LENGTH_SHORT);
tempMessage.show();
}

}

What could be the problem?...i am a beginner in Android development
Posted

The first parameter to the makeText call should be an Activity instance, in your case it looks like you've copied a click-handler that was previously an anonymous type inside MainActivity. But since Toaster is not part of MainActivity you could try passing the Activity in to the Toaster.

Change your code to;
Java
public class Toaster implements OnClickListener {

  private final MainActivity mainActivity;

  public Toaster(final MainActivity mainActivity) {
    this.mainActivity = mainActivity;
  }
 
  @Override
  public void onClick(View clickedButton) {  
    final String greetingText = "Hello from Android!";
    final Toast tempMessage = Toast.makeText(mainActivity, greetingText, Toast.LENGTH_SHORT);
    tempMessage.show();
  }
}

and make sure to pass the instance of MainActivity to Toaster when calling it's constructor.

Hope this helps,
Fredrik
 
Share this answer
 
Well try this out,
Java
public class Toaster implements OnClickListener {

    Context ctx = this; 
    
    @Override
    public void onClick(View clickedButton) 
    {
        String greetingText = "Hello from Android!";
        Toast.makeText(cyx , greetingText, Toast.LENGTH_SHORT).show();
    }
 
}

-KR
 
Share this answer
 
You can create the Toaster class inside the MainActivity.
public class MainActivity extends Activity {
	
	public class Toaster implements OnClickListener {

		@Override
		public void onClick(View clickedButton) {

			String greetingText = "Hello from Android!";

			Toast tempMessage = Toast.makeText(MainActivity.this, greetingText,
					Toast.LENGTH_SHORT);
			tempMessage.show();
		}

	}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900