0

我试图通过以下实验室来学习https://sites.google.com/site/androidcoursearchive/labs/lab-1

这是代码

名称Getter.java

public class NameGetter extends Activity implements OnClickListener {

    EditText name;
    Button submit;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.name_getter);
        name = (EditText) this.findViewById(R.id.editText1);
        submit = (Button) this.findViewById(R.id.button1);
        submit.setOnClickListener(this);
    }

    public void onClick(View v) {
        String userName = name.getText().toString();
        Intent submitIntent = new Intent(NameGetter.this, HelloWorld.class);
        submitIntent.putExtra("username", userName);
        this.startActivity(submitIntent);
    }
}

HelloWorld.java

public class HelloWorld extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView tv = (TextView) this.findViewById(R.id.textViewHello);

        Bundle name = this.getIntent().getExtras();

        if(name != null) {
            String nameEntered = name.getString("username");
            if(nameEntered != null) {
                tv.setText(nameEntered);
            } else {
                tv.setText("nameEntered is null");
            }
        } else {
            tv.setText("name is null");
        }
    }
}

我可以在 EditText 框中输入文本,当我按下提交按钮时,我会强制关闭。LogCat 说如下:

java.lang.RuntimeException:无法启动活动 ComponentInfo{com.mypackagerhello.com/com.mypackagerhello.com.HelloWorld}:java.lang.NullPointerException`

编辑:谢谢大家!这是this.setContentView(R.layout.main);HelloWorld.java 中缺少的行。

4

3 回答 3

1

请注意,在 NameGetter Activity 中,您将内容视图设置为:

this.setContentView(R.layout.name_getter);

但是在您的 HelloWorld 活动中,您还没有这样做。在 super.onCreate 之后和 findViewById 之前添加该行。祝你好运!

于 2012-06-05T06:58:25.527 回答
0

插入

setContentView(R.layout.<layout_id>);

在HelloWorld之前

TextView tv = (TextView) this.findViewById(R.id.textViewHello);
于 2012-06-05T06:57:42.267 回答
0

jsut 在 androidmanifest.xml 中的 aplication 标记中声明您的 HelloWorld 活动,如下所示

        <activity
            android:name=".HelloWorld"
            android:label="@string/app_name" >
        </activity>
于 2012-06-05T07:04:40.837 回答