有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java天文钟模拟器

他是java新手,正在学习从头开始构建计时器应用程序的教程。 应用程序可以编译,但在emulator中按start或stop时,应用程序崩溃。 在没有通知的情况下启动应用程序, 暂停带有崩溃通知的崩溃应用程序并填写报告建议, 停止不崩溃,但什么也不做。 我已经搜索了很多关于它的网站,似乎没有发现任何问题

主要活动java

package com.example.dayswithout;

import 安卓x.appcompat.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.os.SystemClock;
import 安卓.view.View;
import 安卓.widget.Chronometer;
import 安卓.widget.Toast;


public class MainActivity extends AppCompatActivity {
    private Chronometer chronometer;
    private long pauseOffset;
    private Boolean running;

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

        chronometer=findViewById(R.id.chronometer);
        chronometer.setFormat("Time: %s");
        chronometer.setBase(SystemClock.elapsedRealtime());
        chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 10000) {
                    chronometer.setBase(SystemClock.elapsedRealtime());
                    Toast.makeText(MainActivity.this, "Bing!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void startChronometer(View v){
        if(!running) {
            chronometer.setBase(SystemClock.elapsedRealtime()-pauseOffset);
            chronometer.start();
            running = true;
        }
    }
    public void pauseChronometer(View v){
        if(running) {
            chronometer.stop();
            pauseOffset=SystemClock.elapsedRealtime()-chronometer.getBase();
            running = false;
        }
    }
    public void resetChronometer(View v){
        chronometer.setBase(SystemClock.elapsedRealtime());
        pauseOffset=0;
    }
}

活动主xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical"
    安卓:gravity="center"
    tools:context=".MainActivity">

    <Chronometer
        安卓:id="@+id/chronometer"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:textSize="30sp" />
    <Button
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:onClick="startChronometer"
        安卓:text="Start"/>
    <Button
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="Pause"
        安卓:onClick="pauseChronometer"/>
    <Button
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="reset"
        安卓:onClick="resetChronometer"/>
</LinearLayout>

日志

02/22 14:19:49: Launching 'app' on No Devices.
Install successfully finished in 1 s 718 ms.
$ adb shell am start -n "com.example.dayswithout/com.example.dayswithout.MainActivity" -a 安卓.intent.action.MAIN -c 安卓.intent.category.LAUNCHER
Connected to process 6915 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/ple.dayswithou: Not late-enabling -Xcheck:jni (already on)
I/ple.dayswithou: Unquickening 12 vdex files!
W/ple.dayswithou: 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/ple.dayswithou: Accessing hidden method L安卓/view/View;->computeFitSystemWindows(L安卓/graphics/Rect;L安卓/graphics/Rect;)Z (greylist, reflection, allowed)
W/ple.dayswithou: Accessing hidden method L安卓/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xebb41ac0, tid 7013
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: 0xebb41a50: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xebb41a50: ver 2 0 (tinfo 0xebe96950) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
    HostConnection::get() New Host Connection established 0xebb41eb0, tid 7013
D/goldfish-address-space: allocate: Ask for block of size 0x100
    allocate: ioctl allocate returned offset 0x3fbda9000 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=1037ms; Flags=1, IntendedVsync=748790555628, Vsync=748807222294, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=748815462000, AnimationStart=748815491400, PerformTraversalsStart=748816913000, DrawStart=749730608800, SyncQueued=749763725800, SyncStart=749765306700, IssueDrawCommandsStart=749765382800, SwapBuffers=749827691200, FrameCompleted=749829712000, DequeueBufferDuration=138600, QueueBufferDuration=791000, GpuCompleted=-2920196950870201425, 
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dayswithout, PID: 6915
    java.lang.IllegalStateException: Could not execute method for 安卓:onClick
        at 安卓x.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
        at 安卓.view.View.performClick(View.java:7448)
        at com.google.安卓.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at 安卓.view.View.performClickInternal(View.java:7425)
        at 安卓.view.View.access$3600(View.java:810)
        at 安卓.view.View$PerformClick.run(View.java:28305)
        at 安卓.os.Handler.handleCallback(Handler.java:938)
        at 安卓.os.Handler.dispatchMessage(Handler.java:99)
        at 安卓.os.Looper.loop(Looper.java:223)
        at 安卓.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.安卓.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at 安卓x.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
        at 安卓.view.View.performClick(View.java:7448) 
        at com.google.安卓.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
        at 安卓.view.View.performClickInternal(View.java:7425) 
        at 安卓.view.View.access$3600(View.java:810) 
        at 安卓.view.View$PerformClick.run(View.java:28305) 
        at 安卓.os.Handler.handleCallback(Handler.java:938) 
        at 安卓.os.Handler.dispatchMessage(Handler.java:99) 
        at 安卓.os.Looper.loop(Looper.java:223) 
        at 安卓.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.安卓.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
        at com.example.dayswithout.MainActivity.startChronometer(MainActivity.java:35)
        at java.lang.reflect.Method.invoke(Native Method) 
        at 安卓x.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
        at 安卓.view.View.performClick(View.java:7448) 
        at com.google.安卓.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
        at 安卓.view.View.performClickInternal(View.java:7425) 
        at 安卓.view.View.access$3600(View.java:810) 
        at 安卓.view.View$PerformClick.run(View.java:28305) 
        at 安卓.os.Handler.handleCallback(Handler.java:938) 
        at 安卓.os.Handler.dispatchMessage(Handler.java:99) 
        at 安卓.os.Looper.loop(Looper.java:223) 
        at 安卓.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.安卓.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 6915 SIG: 9

共 (2) 个答案

  1. # 1 楼答案

    该错误表示您的对象未实例化:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference

    Boolean是一种Object类型,一种引用类型,需要实例化。在您的例子中private Boolean running;是声明的,但它从未被实例化,导致上面的NullPointerException

    相反,将类型从Boolean更改为primitveboolean。您没有来初始化它,因为它将使用默认值false。然而,为了可读性,初始化它可能是明智的

    private boolean running = false;

  2. # 2 楼答案

    这里有一个问题:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
            at com.example.dayswithout.MainActivity.startChronometer(MainActivity.java:35)
    

    这表示running变量未初始化:

    public void startChronometer(View v){
            if(!running) {
    

    我建议将它从包装的Boolean更改为一个对象且未设置,因此它的值为null。到声明中的基元boolean

    private Boolean running;
    ->
    private boolean running = false;
    

    对于Clarity,可能将其设置为false(可选,因为false是默认值)