单击按钮后应用程序崩溃

时间:2015-12-09 01:36:04

标签: java android xml

我正在关注Google的Android开发教程。我一开始就遇到了问题但似乎无法解决问题。 http://developer.android.com/training/basics/firstapp/starting-activity.html#ReceiveIntent

每当我点击"发送"按钮,我的应用程序崩溃而不是打开新活动。

我最初的家庭活动的XML:

</LinearLayout>
    <EditText
    android:id="@+id/edit_message"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />

    <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"/>
</LinearLayout>

Home.Java文件中的sendMessage方法

public void sendMessage(View view){
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

新活动的Java

    //Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(Home.EXTRA_MESSAGE);

    //Creating the textview
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    //Set text view as activity layout
    setContentView(textView);

主要错误:

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {appfactree.me.dotnotes / appfactree.me.dotnotes.DisplayMessageActivity}:   java.lang.NullPointerException:尝试调用虚方法   &#39; java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()&#39;   在空对象引用上

请询问您是否还需要其他任何东西。 非常感谢您的帮助。

编辑:根据要求提供完整的DisplayMessageActivity.java代码:

public class DisplayMessageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(Home.EXTRA_MESSAGE);

    //Creating the textview
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    //Set text view as activity layout
    setContentView(textView);
    }
}

1 个答案:

答案 0 :(得分:0)

你的LinearLayout很轻微...你有一个打开LinearLayout的结束标记。用户而不是第一行的开头标记。

这不是问题的原因。它似乎与您的工具栏有关...但是无法解释您发布的代码中的确切内容。

相关问题