user3182266
user3182266

Reputation: 1330

Android widget relativelayout cannot be cast to android widget textview

bI have the following java code:

    Intent intent = getIntent();

    CO2 = intent.getIntExtra("CO2", 0);     

    TextView textCo2 = (TextView)findViewById(R.id.textRoadView1);
    textCo2.setText(String.valueOf("CO2 emissions: "+CO2+"g"));

And the XML file:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/textRoadView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".RoadDetails" >

    <TextView
    android:id="@+id/textRoadView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="38dp"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />
    </RelativeLayout>

So when I try to set some text in the "textCo2" I get this weird exception "Android widget relativelayout cannot be cast to android widget textview." I tried removing the "R.java" file and cleaning the project but the problem continued. I think the mistake is somewhere in my code but I can find it. Could you help me out?

Upvotes: 2

Views: 8202

Answers (1)

Damien R.
Damien R.

Reputation: 3373

Your id is duplicate, remove if from your RelativeLayout, like this:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".RoadDetails" >

    <TextView
    android:id="@+id/textRoadView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="38dp"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />
    </RelativeLayout>

Upvotes: 8

Related Questions