E2ma
E2ma

Reputation: 21

Dynamic Strings and Xml

I'm new to Android (and surely I'm not an expert Java developer), so I'm sorry for the dumb question

I would like to "capture" the id of a textView and to set its text value dynamically, here is how I'm trying to do this:

public class AndStringTestActivity extends Activity {
/** Called when the activity is first created. */

String abc = "abcabc";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView tv = (TextView)findViewById(R.id.test);
    tv.setText(abc);

    setContentView(R.layout.main);
}
}

and here is the Xml from which i'm reading the id of the textview i would like to write inside

// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView  
android:id="@+id/test"
android:layout_width="fill_parent"
android:layout_height="fill_parent"    
/> 
</LinearLayout>

the error i receive is the usual Application stopped unexpectedly

Thanks.

Upvotes: 2

Views: 158

Answers (2)

hrnt
hrnt

Reputation: 10142

Call setContentView before trying to find the TextView. The TextView does not exist before you have called setContentView (which will inflate your XML layout)

Upvotes: 5

DeeV
DeeV

Reputation: 36035

Call setContentView(R.layout.main) before you call findViewById().

Upvotes: 3

Related Questions