繁体   English   中英

Android Studio:SecondActivity 关闭

[英]Android Studio: SecondActivity closes

我试图在 SecondActivity 中传递一些变量,但是当我按下 MainActivity 上的按钮时,应用程序关闭并且没有出现错误。

这是 MainActivity.java 的代码:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends AppCompatActivity {
    
    private Button button;

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

        
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, SecondActivity.class);

                i.putExtra("name", "Teresa");
                i.putExtra("age", 31);

                startActivity(i);
            }

        });
    }
}

这是activity_main.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next"
        tools:layout_editor_absoluteX="161dp"
        tools:layout_editor_absoluteY="218dp" />

</LinearLayout>

这是SecondActivity.java的代码:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public abstract class SecondActivity extends AppCompatActivity {

    Bundle resultIntent = getIntent().getExtras();



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

        String nameValue = resultIntent.getString("name");
        int ageValue = resultIntent.getInt("age");

        TextView nameValueTxt = (TextView) findViewById(R.id.nameValue);
        TextView ageValueTxt = (TextView) findViewById(R.id.ageValue);

        nameValueTxt.setText(nameValue);
        ageValueTxt.setText(ageValue);

    }
}

这是activity_second.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".SecondActivity">

    <TextView
        android:id="@+id/ageValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ageValue" />

    <TextView
        android:id="@+id/nameValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="nameValue" />
</LinearLayout>

这是AndroidManifest.xml的代码:

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

    <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/Theme.MyApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".SecondActivity">
        </activity>
    </application>

</manifest>

我在等你的帮助。

谢谢你。

编辑:这些是日志:

03/18 16:18:16: Launching 'app' on No Devices.
Install successfully finished in 2 s 963 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 10457 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/e.myapplicatio: Not late-enabling -Xcheck:jni (already on)
I/e.myapplicatio: Unquickening 12 vdex files!
W/e.myapplicatio: Unexpected CPU variant for X86 using defaults: x86
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xf682b4a0, tid 10480
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf680c330: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xf680c330: ver 2 0 (tinfo 0xf6b777b0) (first time)
I/e.myapplicatio: Background young concurrent copying GC freed 21439(1612KB) AllocSpace objects, 0(0B) LOS objects, 91% free, 2358KB/26MB, paused 55.782ms total 950.331ms
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xf68216b0, tid 10480
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fbe8d000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2 
I/OpenGLRenderer: Davey! duration=748ms; Flags=1, IntendedVsync=1439181210264, Vsync=1439181210264, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=1439193561700, AnimationStart=1439193630300, PerformTraversalsStart=1439194044200, DrawStart=1439746856100, SyncQueued=1439804466100, SyncStart=1439809568000, IssueDrawCommandsStart=1439809792200, SwapBuffers=1439908675700, FrameCompleted=1439934859000, DequeueBufferDuration=397200, QueueBufferDuration=3050600, GpuCompleted=72904454231491230, 
I/Choreographer: Skipped 51 frames!  The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=914ms; Flags=0, IntendedVsync=1439231225961, Vsync=1440081225927, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=1440093164200, AnimationStart=1440093239300, PerformTraversalsStart=1440094146300, DrawStart=1440100820200, SyncQueued=1440102126800, SyncStart=1440103223300, IssueDrawCommandsStart=1440103359000, SwapBuffers=1440109527000, FrameCompleted=1440146626900, DequeueBufferDuration=1638000, QueueBufferDuration=3213800, GpuCompleted=43984843964424, 
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 10457
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.SecondActivity}: java.lang.InstantiationException: java.lang.Class<com.example.myapplication.SecondActivity> cannot be instantiated
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.example.myapplication.SecondActivity> cannot be instantiated
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
  1. 从 SecondActivity 中删除抽象关键字。
  2. 在 OnCreate Mehtod 中以 Bundle 的形式从 Intent 中获取 Extras。
  3. 使用ageValueTxt.setText(String.valueOf(ageValue)); 而不是ageValueTxt.setText(ageValue);

你的 SecondActivity 应该看起来像

public class SecondActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    Bundle resultIntent = getIntent().getExtras();

    String nameValue = resultIntent.getString("name");
    int ageValue = resultIntent.getInt("age");

    TextView nameValueTxt = (TextView) findViewById(R.id.nameValue);
    TextView ageValueTxt = (TextView) findViewById(R.id.ageValue);

    nameValueTxt.setText(nameValue);
    ageValueTxt.setText(String.valueOf(ageValue));
}

}

这应该在onCreate()中你不能从onCreate() scope 中初始化它。

Bundle resultIntent = getIntent().getExtras();

在您的情况下, resultIntent将包含 null ,这就是您的应用程序崩溃的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM