Skip to content Skip to sidebar Skip to footer

Classcastexception: Android.widget.relativelayout Cannot Be Cast To Android.widget.textview?

I'm trying to type cast data but when I write TextView clickData=(TextView) view under onItemClick(...) logcat shows msg: java.lang.ClassCastException: android.widget.RelativeLayo

Solution 1:

That view you want to access its the RelativeLayout you show on second xml. If you want to access the TextView you have to find it on that RelativeLayout.

Instead of this

TextView clickData=(TextView) view;

try this

TextView clickData=(TextView) view.findViewById(R.id. textView5);

I think this resolves your problem

Updated...

My suggestion is to use an Adapter

public class YourAdapter extends BaseAdapter {

private ArrayList<Things> things;
private Context context;
private TextView yearTxtView;
private TextView weekTxtView;
private TextView extraTxtView;


publicYourAdapter(Context context, ArrayList<Things> things) {
    this.things = things;
    this.context = context;
}

@OverridepublicintgetCount() {
    returnthis.things.size();
}

@Overridepublic Object getItem(int position) {
    returnthis.things.get(position);
}

@OverridepubliclonggetItemId(int position) {
    return position;
}

@Overridepublic View getView(int position, View convertView, ViewGroup parent) {
    convertView =     LayoutInflater.from(this.context).inflate(R.layout.ITEM_LAYOUT, parent, false);

    convertView.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
            //do your code here
        }
    });

    return convertView;


}

}

and on that code you have, just do this

private YourAdapter yourAdapter;

this.yourAdapter = new YourAdapter(getActivity(),YourArray);

myListView.setAdapter(this.yourAdapter);

Solution 2:

It seems like the Android compiler has become very specific. I encountered the same problem, and it is a pity because this is the kind of code that is on every sample program and Android developer forum or guide. The solution is to treat the compiler by feeding it exactly what it is asking for and in this case the textview (android.widget.TextView).

REMOVE the layout frame (LinearLayout, RelativeLayout, etc) around the TextView and trust that on inflating within the ListView parent widget, it will "find its way in the code world". So, set it free.

So you can define the properties of the TextView as you need, DECLARE the android schema (xmlns:android="http://schemas.android.com/apk/res/android") in the TextView itself. After this, the compile won't be confused and everything should compile.

Post a Comment for "Classcastexception: Android.widget.relativelayout Cannot Be Cast To Android.widget.textview?"