I am a beginner of android, and was studying the layout.
What i am trying to do is i am trying to add a textView to a LinearLayout through code, and the application stops with the error that the application has stopped unexpectedly. The code is:
setContentView(R.layout.main);
LinearLayout abc = (LinearLayout)findViewById(R.id.cLayout);
TextView tv = new TextView(this);
tv.setText("Text Changed!!!!");
abc.addView(tv);
And in the xml, id is set like: android:id=”@+id/cLayout”.
I know there are better ways to do it, but i want to know why this doesn’t work. Contents of textView are changing just fine. Also i have also tried
LinearLayout abc = (LinearLayout)findViewById(R.layout.main);
What am i doing wrong? One thing is clear that i am accessing uncreated items (unassigned pointer).
Edit
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"
android:id="@+id/cLayout"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World"
android:id="@+id/myTV"
/>
</LinearLayout>
I’ve tried to reproduce it, and it works for me, no exceptions.
main.xml:
MyActivity.java:
UPD When I posted your code, I got an exception, too. Make sure you call
super.onCreate().