Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to apply a variable to a toast?

Tags:

java

android

I'm going to be using a toast in my application for testing purposes. I am only new to the Android environment and I'm not very familiar with toasts. I know a standard toast it like this: Toast.makeText(context, text, duration).show();. However, instead of applying a String of text into the 'text' section, I want to apply a variable.

Here is what I have written:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_next);


    Button send = (Button) findViewById(R.id.bSend);//Import button1 (Send)

    send.setOnClickListener(new OnClickListener() {//Set an onClickListener for the button to work

        public void onClick(View v) {

            Toast.makeText(getApplicationContext(), cText, Toast.LENGTH_LONG).show();

        }//end method

    });//End Send


}//End onCreate

cText is a variable used in a different method present in the class. Any suggestions on how I can get the toast to contain the contents of cText? Thanks in advance.

like image 748
user2261396 Avatar asked Nov 04 '22 00:11

user2261396


1 Answers

May be you an Try this

public class MainActivity extends Activity {
String Text="MainActivity  Message"; //Global variable

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_screen_next);
 Button send = (Button) findViewById(R.id.bSend);//Import button1 (Send)

    send.setOnClickListener(new OnClickListener() {//Set an onClickListener for the button to work

    public void onClick(View v) {

       //Declaring two variables.
       //You can also declare it as global.
       //but global variable must be initialized before creating toast otherwise you will get NPE and lead to you application crash
       String cText="Toast Message";
       int val=1;

       Toast.makeText(getApplicationContext(), cText, Toast.LENGTH_LONG).show();

       Toast.makeText(getApplicationContext(), "vlaue is "+val, Toast.LENGTH_LONG).show();

       Toast.makeText(getApplicationContext(), getMessage(), Toast.LENGTH_LONG).show(); 

    }

});

    }
  public String getMessage(){
     return "Text from Function";
  }
}
like image 63
edwin Avatar answered Nov 11 '22 12:11

edwin