0

I want to put ArrayList on onClick method. But it tell me i should change arraylist to final(i will put something in there so can't). how should i put arraylist in it!?

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView txt1;
    Button btn1;


     ArrayList <String> shop= new ArrayList <String>();
    impshop(shop);

    txt1 =(TextView)findViewById(R.id.tv1);
    btn1 =(Button)findViewById(R.id.button1);

    btn1.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Random ran = new Random();
            int choose = ran.nextInt(shop.size());  
            txt1.setText(shop.get(choose));
        }});

}

can i onClick(View v,ArrayList shop) ?

2
  • usually, eclipse gives you an error, and the quick fix is too make the variable final, which effectively solves the issue. Commented Nov 5, 2013 at 15:46
  • I think you can't do it, since the OnClickListener must implement the inherited abstract method onClick(View) Commented Nov 5, 2013 at 15:54

3 Answers 3

1

Besides adding final to your ArrayList, you may also define it outside onCreate method. Doing so does not require you to define final modifier.

Though be sure to not use the ArrayList to store elements that belong to the Activity's Context or elements that might be linked to other contexts of the application, failing to do so might result in big memory leaks.

Sign up to request clarification or add additional context in comments.

Comments

0

Add final before

ArrayList <String> shop= new ArrayList <String>();

so it looks like:

final ArrayList <String> shop= new ArrayList <String>();

Comments

0
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView txt1;
    Button btn1;

    final ArrayList <String> shop= new ArrayList <String>();
    impshop(shop);

    txt1 =(TextView)findViewById(R.id.tv1);
    btn1 =(Button)findViewById(R.id.button1);

    btn1.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Random ran = new Random();
        int choose = ran.nextInt(shop.size());  
        txt1.setText(shop.get(choose));
    }});
}

or declare your ArrayList as a field

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.