点击按钮进入第二个活动时会自动关闭应用程序 [Android Studio]

huangapple go评论80阅读模式
英文:

Clicking the button to second activity automatically closes app [Android Studio]

问题

以下是翻译好的部分:

Background

只是为了提供一些背景信息,我对Android应用程序开发非常陌生。在使用Android开发者指南开发一个教我如何创建一个“Hello, World!”项目的基本应用程序之后,我尝试学习如何构建用户界面并启动另一个活动。最终,主要关注的是在MainActivity中添加一些代码,以在用户点击“发送”按钮时启动一个新的活动来显示一条消息。在将应用程序运行在我的设备上之后,我尝试输入一条消息并点击发送,但发送按钮最终关闭了我的应用程序,没有任何延迟,也没有解释为什么关闭了应用程序。

MainActivity.java

package com.example.giglitz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class MainActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user taps the send button */
    public void sendMessage(View view)  {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.editText);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.giglitz">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".DisplayMessageActivity">
            android:parentActivityName=".MainActivity">
            <!-- 如果您支持API级别为15或更低级别,则需要meta-data标签 -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

DisplayMessageActivity.java

package com.example.giglitz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        // 获取启动此活动的Intent并提取字符串
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        // 获取布局的TextView并将字符串设置为其文本
        TextView textView = findViewById(R.id.textView);
        textView.setText(message);
    }
}

activity_display_message.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DisplayMessageActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Logcat(在过滤错误后,只显示选定应用程序)

Process: com.example.giglitz, PID: 6422
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
        at android.view.View.performClick(View.java:7201)
        at android.view.View.performClickInternal(View.java:7170)
        at android.view.View.access$3500(View.java:806)
        at android.view.View$PerformClick.run(View.java:27562)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
        at android.view.View.performClick(View.java:7201)
        at android.view.View.performClickInternal(View.java:7170)
        at android.view.View.access$3500(View.java:806)
        at android.view.View$PerformClick.run(View.java:27562)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.giglitz.MainActivity.sendMessage(MainActivity.java:24)
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
        at android.view.View.performClick(View.java:7201)
        at android.view.View.performClickInternal(View.java:7170)
        at android.view.View.access$3500(View.java:806)
        at android.view.View$PerformClick.run(View.java:27562)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)


<details>
<summary>英文:</summary>

## **Background** ##

Just to set some context, I&#39;m very new to Android app development. After using Android Developers guide on developing a basic app that would teach me how to create a &quot;Hello, World!&quot; project. However, after learning to build a user interface and start another activity. Ultimately, the main focus was to add some code to the MainActivity that starts a new activity to display a message when the user would tap the Send button. After running the app on my device, I attempted to type out a message and click send, only for the send button to ultimately close my app with no lag, or explaination as to why it closed.

**MainActivity.java**

package com.example.giglitz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

/** Called when the user taps the send button */
public void sendMessage(View view)  {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}

}


**AndroidManifest.xml**

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.giglitz">

&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;activity android:name=&quot;.DisplayMessageActivity&quot;&gt;
android:parentActivityName=&quot;.MainActivity&quot;&gt;
&lt;!-- The meta-data tag is required if you support API level 15 and lower --&gt;
&lt;meta-data
android:name=&quot;android.support.PARENT_ACTIVITY&quot;
android:value=&quot;.MainActivity&quot; /&gt;
&lt;/activity&gt;
&lt;activity android:name=&quot;.MainActivity&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;

</manifest>


**DisplayMessageActivity.java**

package com.example.giglitz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout&#39;s TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}

}


**activity_display_message.xml**

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">

&lt;TextView
android:id=&quot;@+id/textView&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginTop=&quot;16dp&quot;
android:text=&quot;TextView&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

</androidx.constraintlayout.widget.ConstraintLayout>


**Logcat (after filtering Error, Show only selected application)**

Process: com.example.giglitz, PID: 6422
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
at android.view.View.performClick(View.java:7201)
at android.view.View.performClickInternal(View.java:7170)
at android.view.View.access$3500(View.java:806)
at android.view.View$PerformClick.run(View.java:27562)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:7201) 
at android.view.View.performClickInternal(View.java:7170) 
at android.view.View.access$3500(View.java:806) 
at android.view.View$PerformClick.run(View.java:27562) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7682) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.giglitz.MainActivity.sendMessage(MainActivity.java:24)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:7201) 
at android.view.View.performClickInternal(View.java:7170) 
at android.view.View.access$3500(View.java:806) 
at android.view.View$PerformClick.run(View.java:27562) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7682) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 


**activity_main.xml**

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

&lt;EditText
android:id=&quot;@+id/editTextTextPersonName&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginLeft=&quot;16dp&quot;
android:layout_marginTop=&quot;16dp&quot;
android:ems=&quot;10&quot;
android:hint=&quot;@string/edit_message&quot;
android:inputType=&quot;textPersonName&quot;
app:layout_constraintEnd_toStartOf=&quot;@+id/button&quot;
app:layout_constraintHorizontal_bias=&quot;0.5&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;Button
android:id=&quot;@+id/button&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginLeft=&quot;16dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:layout_marginRight=&quot;16dp&quot;
android:onClick=&quot;sendMessage&quot;
android:text=&quot;@string/button_send&quot;
app:layout_constraintBaseline_toBaselineOf=&quot;@+id/editTextTextPersonName&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.5&quot;
app:layout_constraintStart_toEndOf=&quot;@+id/editTextTextPersonName&quot; /&gt;

</androidx.constraintlayout.widget.ConstraintLayout>


</details>
# 答案1
**得分**: 1
我认为你要么没有在按钮的 'onclick' 字段中放入任何内容,要么没有为你的 EditText 设置ID。你能发送你的 activity_main.xml 文件吗?如果你想知道它在哪里,进入 'res' 目录,然后进入 'layout' 目录。
<details>
<summary>英文:</summary>
I think you either did not put anything in the &#39;onclick&#39; field for your button, or you didn&#39;t set an ID for your EditText. Can you send your activity_main.xml file as well? If you want to know where it is, go to the &#39;res&#39; directory, and then go into the &#39;layout&#39; directory.
</details>
# 答案2
**得分**: 0
我需要查看您的日志输出以确定您遇到了什么问题。通常在使用意图附加信息(Intent extras)时,我建议检查对象的可为null性,因为该字符串可能不存在,尽管在这种情况下它显然是存在的。所以,请发送您日志的文字记录。谢谢!
<details>
<summary>英文:</summary>
I will need to see your logcat output to determine what problems you encountered. Generally, when using Intent extras, I recommend checking for nullability of objects, as that string might not exist, although it clearly does in this case. So, please send a transcript of your logs. 
Thanks!
</details>
# 答案3
**得分**: 0
好的,以下是您要翻译的内容:
看起来您在应用程序中没有正确实现“onclick”行为。在 XML 文件中,您应该为发送按钮添加这一行:`android:onClick="sendMessage"`
另外,查看以下链接以获取有关在 Android 中实现 onClick 行为的更多详细信息:https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents,https://stackoverflow.com/a/4153842/1725535
<details>
<summary>英文:</summary>
It looks like you did not implement the &#39;onclick&#39; behavior correctly in your app. In the XML file, you should add this line for your send button `android:onClick=&quot;sendMessage&quot;`
Also, check out this for more details about implementing onClick behaviors in Android: https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents, https://stackoverflow.com/a/4153842/1725535
</details>
# 答案4
**得分**: 0
看起来你在应用程序中没有正确实现 'onclick' 行为。在 XML 文件中,你应该为发送按钮添加这一行代码 android:onClick="sendMessage"
这样可以让活动监听按钮点击事件并调用 onClickListener 方法。
<details>
<summary>英文:</summary>
It looks like you did not implement the &#39;onclick&#39; behavior correctly in your app. In the XML file, you should add this line for your send button android:onClick=&quot;sendMessage&quot;
To tell activity to listen the button click and call the onClickListner method.
</details>
# 答案5
**得分**: 0
代码部分不要翻译,只返回翻译好的内容:
似乎您在应用程序中没有正确实现'onclick'行为。在XML文件中,您应该为发送按钮添加这行代码android:onClick="sendMessage",或者您可以通过按钮ID以编程方式使用它。例如:
```java
Button btn = (Button) findViewById(R.id.sendButton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 在这里添加您的语句
}
});

通过这种方式,您可以告诉活动监听按钮点击事件并调用onClickListner方法。

英文:
It looks like you did not implement the &#39;onclick&#39; behavior correctly in your app.
In the XML file, you should add this line for your send button 
android:onClick=&quot;sendMessage&quot;  or you can use it programmatically by button id
For eg:-
Button btn = (Button) findViewById(R.Id.sendButton);
btn.setOnClickListner(new View.OnClickListner){
@Override
public onClick(View view){
// Your statement 
}
}

To tell activity to listen the button click and call the onClickListner method.

huangapple
  • 本文由 发表于 2020年8月23日 03:16:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63540189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定