0

I am trying to extend baseAdapter. and get the object inside onClick event. But its saying that, obj needs to be declared final. Someone, told me that the obj(aStudent) cant be found inside the click event?if so, why?

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) adapterContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.custome_adapter_list_row_item, parent, false);

    TextView lblStudentName = (TextView) rowView.findViewById(R.id.lblStudentName);
    TextView lblStudentAge = (TextView) rowView.findViewById(R.id.lblStudentAge);
    Button btnNext = (Button) rowView.findViewById(R.id.lbllist);

    **final  Student aStudent = studentDataHolder.get(position);**

    if (aStudent != null) {
        lblStudentName.setText(aStudent.getName());
        lblStudentAge.setText("Age : " + aStudent.getAge());

        btnNext.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(adapterContext, "Position is"+aStudent.getName(), Toast.LENGTH_LONG).show();
            }
        });



    }
    return rowView;

}

as, far as i understand, the code is making a new object of Student everytime its fetching a row from the array. Am i wrong? But still again, why final?

shaon007
  • 163
  • 3
  • 16
  • See http://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class/4732617 – laalto Feb 03 '14 at 15:57

2 Answers2

2

This took some time for me to understand but here is my reasoning. When you declare a variable as final you are "telling" the compiler(among other things) that this variable should be available even after the local scope goes away and that it cannot be reassigned once instantiated. To clarify, you are declaring the listener as an inner class. The listener will trigger when the Button is pressed. The Button might be pressed long after the getView() has finished executing and it is removed from the stack. This will cause a problem because aStudent will not be in memory anymore. By declaring it final, aStudent will be retained even after the method is removed from the stack.

Emmanuel
  • 13,083
  • 4
  • 39
  • 53
1

You need to make it final because you are using it in a annonymous inner class.

The below link gives a better explanation

Why Java inner classes require "final" outer instance variables?

Quoting

An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256