Syed Ariff Syed Ariff - 3 months ago 13
Java Question

CharSequence in Toast animation not appearing? Android

I am fairly new to Android development so here is my problem.
I have an array of buttons which I would like to display a

Toast
saying "This button will launch" + the button's getText value when pressed.

EDIT

The declaration and initialization code of the buttons array.

final Button buttons[] = new Button[6];
buttons[0] = (Button) findViewById(R.id.button1);
buttons[1] = (Button) findViewById(R.id.button2);
buttons[2] = (Button) findViewById(R.id.button3);
buttons[3] = (Button) findViewById(R.id.button4);
buttons[4] = (Button) findViewById(R.id.button5);
buttons[5] = (Button) findViewById(R.id.button6);


So,

for(i = 0; i< buttons.length; i++){
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Log.d("test","Why is this not appearing in logcat");
CharSequence buttonvalue = buttons[i].getText();
Context context = getApplicationContext();
System.out.println(buttonvalue);
CharSequence text = "This button will launch" + buttonvalue + " App!!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}


The app compiles fine but crashes as soon as I pressed the buttons.And I can't seem to debug it cause both
System.out.println()
and Logcat is not appearing at all or I am just looking at the wrong place. Where should I find these messages then?

Component Tree:
enter image description here
Here is a screenshot :
enter image description here

Answer

Try to follow my example it's more simple to implement while you dont have a LogCat:

 private static final int[] idArray = {R.id.button0, R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5};

private Button[] bt = new Button[idArray.length];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_layout);

    for (int i=0; i<idArray.length; i++) {
        final int b = i;
        bt [b] = (Button)findViewById(idArray[b]); // Fetch the view id from array
        bt [b].setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

 Toast.makeText(getApplicationContext(),"This button will launch" + bt[b].getText().toString() + " App!!";,Toast.LENGTH_LONG).show();                }
        });

    }
}