Issue
I'm trying to create a program for Android which will read in text, and then print it out, jsut to get used to using I/O for Android. However, whenever I run it on the AVD, it returns an error in LogCat saying that there is a NullPointerException in my code, and that it is therefore "unable to instantiate activity ComponentInfo".
I can't find where I'm referring to anything null.
Here is my code:
import android.app.*;
import android.os.*;
import android.view.View;
import android.view.View.*;
import android.widget.*;
public class ButtonTestActivity extends Activity {
TextView tv = (TextView) findViewById(R.id.textView1);
EditText et = (EditText) findViewById(R.id.edittext);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.Enter);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
tv.setText(et.getText().toString());
}
});
}
}
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/Enter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Does anyone know what could be causing this? Thanks a lot.
Solution
You need to instantiate your views inside onCreate and after the setContentView, the Activity doesn't know which views you are referring until you set the Activities layout via the setContentView method. If this doesn't fix the problem it would help if you posted the stack trace from LogCat so the exact line number is known.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
EditText et = (EditText) findViewById(R.id.edittext);
Button b = (Button) findViewById(R.id.Enter);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
tv.setText(et.getText().toString());
}
});
}
Answered By - mmaitlen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.