tags:

views:

174

answers:

1

I'm learning android/java and have this example code I can't get to work:

OnRatingBarChangeListener l = new OnRatingBarChangeListener() {
 public void onRatingChanged(RatingBar ratingBar, float rating,
   boolean fromTouch) {
  Integer myPos=(Integer)ratingBar.getTag();
  RowModel model=getModel(myPos);
  model.rating = rating;

  LinearLayout p=(LinearLayout)ratingBar.getParent();
  TextView l=(TextView)p.findViewById(R.id.label);
  l.setText(model.toString());
 }
};

Everything works except the LinearLayout / getParent() downcast. At runtime it creates a ClassCastException. If I comment out that block of code then everthing works fine. What am I missing?

A: 

Well, ratingBar.getParent() doesn't return a LinearLayout. Find out what static type ratingBar.getParent() returns, and use (a reference of ) that type to assign to.

Perhaps you think that ratingBar is-a LinearLayout, and you're confused about Java precedence? Method call operator . has higher precedence than the cast operator (type). It's unlikely, but maybe you meant to do this:

LinearLayout p=( (LinearLayout)ratingBar ).getParent();
tpdi
I have added the following to see what is returned: selection.setText(ratingBar.getParent().toString());and the output is as follows: android.widget.LinearLayout@4377c0a8
Preformed Cone