简体   繁体   中英

Android App Crashing When changing Activity

Trying to Make a Simple TO-DO app with a login and Main Page but it keeps crashing when I try to Switch to the MainPage Activity. I get the Toast to notify that login was successful but the app just closes right after without any warnings or errors. Any help is appreciated!

LoginActivity.java-

package com.example.foodwaste;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;

public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView username = (TextView) findViewById(R.id.username);
        TextView password = (TextView) findViewById(R.id.password);
        MaterialButton login = findViewById(R.id.LoginButton);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(username.getText().toString().equals("test") && password.getText().toString().equals("test")){
                    Toast.makeText(LoginActivity.this, "Logged In! ", Toast.LENGTH_SHORT).show();
                    MainPageActivity();
                }else{
                    Toast.makeText(LoginActivity.this, "Wrong Username or Password! ", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void MainPageActivity(){
        Intent intent = new Intent(LoginActivity.this,MainPage.class);
        startActivity(intent);
    }
}

activity_main.xml-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="@drawable/foodbackground"
    tools:context=".LoginActivity">

    <TextView
        android:id="@+id/signin"
        android:layout_width="match_parent"
        android:layout_height="104dp"

        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="237dp"
        android:layout_marginEnd="0dp"
        android:layout_marginBottom="391dp"
        android:gravity="center"
        android:text="Sign in"
        android:textColor="@color/black"
        android:textSize="40dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/username"
        android:layout_width="299dp"
        android:layout_height="83dp"
        android:layout_alignParentStart="true"

        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="324dp"
        android:layout_marginEnd="112dp"
        android:layout_marginBottom="324dp"
        android:drawableLeft="@drawable/person_asset"
        android:drawablePadding="5dp"
        android:hint="@string/username"
        android:textColor="@color/black"
        android:inputType="text"
        android:imeOptions="actionDone"
        />

    <EditText
        android:id="@+id/password"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="412dp"
        android:layout_marginEnd="111dp"
        android:layout_marginBottom="221dp"
        android:drawableLeft="@drawable/pass_lock"
        android:drawablePadding="5dp"
        android:hint="Password"
        android:inputType="textPassword"
        android:imeOptions="actionDone"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/LoginButton"
        android:layout_width="wrap_content"
        android:layout_height="69dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="74dp"
        android:layout_marginEnd="134dp"
        android:layout_marginBottom="120dp"
        android:backgroundTint="@color/white"
        android:drawableLeft="@drawable/login_button"
        android:drawablePadding="2dp"
        android:text="Login"
        android:textColor="@color/black"
        android:textStyle="bold" />
</RelativeLayout>

MainPage.java-

package com.example.foodwaste;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class MainPage extends AppCompatActivity {
    ArrayList<String> items;
    ArrayAdapter<String> itemAdapter;
    ListView list = findViewById(R.id.list);
    EditText text = findViewById(R.id.itemAdd);
    FloatingActionButton back = findViewById(R.id.back);
    FloatingActionButton newItem = findViewById(R.id.newItem);
    LinearLayout linear_layout = findViewById(R.id.linear_layout);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page2);
    }
}

activity_main_page2.xml -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainPage"
    android:background="@drawable/gradient_2">
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/newItem"
        android:layout_width="71dp"
        android:layout_height="68dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="13dp"
        android:src="@drawable/ic_baseline_add_24"
        tools:ignore="SpeakableTextPresentCheck" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="353dp"
        android:layout_marginBottom="674dp"
        android:src="@drawable/backarr"
        tools:ignore="SpeakableTextPresentCheck" />

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="398dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="58dp"
        android:layout_marginEnd="13dp"
        android:layout_marginBottom="73dp"
        android:orientation="vertical">

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <EditText
        android:id="@+id/itemAdd"
        android:layout_width="339dp"
        android:layout_height="48dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="72dp"
        android:layout_marginBottom="16dp"
        android:ems="10"
        android:hint="Item"
        android:inputType="text"
        android:imeOptions="actionDone"/>

</RelativeLayout>

Logs-

04/26 21:42:27: Launching 'app' on Pixel 2 API 32.
Install successfully finished in 106 ms.
$ adb shell am start -n "com.example.foodwaste/com.example.foodwaste.LoginActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 4879 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/ample.foodwast: Late-enabling -Xcheck:jni
W/re-initialized>: type=1400 audit(0.0:50): avc: granted { execute } for path="/data/data/com.example.foodwaste/code_cache/startup_agents/50cdcce7-agent.so" dev="dm-29" ino=155659 scontext=u:r:untrusted_app:s0:c148,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c148,c256,c512,c768 tclass=file app=com.example.foodwaste
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-88564b4d.jar
W/ample.foodwast: DexFile /data/data/com.example.foodwaste/code_cache/.studio/instruments-88564b4d.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/ample.foodwast: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/ample.foodwast: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10148; state: ENABLED
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.foodwaste' set to: 'default'
V/GraphicsEnvironment: ANGLE GameManagerService for com.example.foodwaste: false
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
W/ample.foodwast: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/ample.foodwast: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xb400007406ea3c50, tid 4900
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_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
D/EGL_emulation: eglCreateContext: 0xb400007406ea3ad0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xb400007406ea3ad0: ver 3 0 (tinfo 0x7620beb080) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xb400007406ea2210, tid 4900
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x1f3ff8000 size 0x8000
W/Gralloc4: allocator 4.x is not supported
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_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
W/System: A resource failed to call close. 
D/EGL_emulation: app_time_stats: avg=184.13ms min=4.24ms max=1935.33ms count=12
D/CompatibilityChangeReporter: Compat change id reported: 163400105; UID 10148; state: ENABLED
D/InputMethodManager: showSoftInput() view=androidx.appcompat.widget.AppCompatEditText{605cbb6 VFED..CL. .F.P..ID 0,851-786,964 #7f0801ce app:id/username aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
I/AssistStructure: Flattened final assist data: 1480 bytes, containing 1 windows, 7 views
D/InsetsController: show(ime(), fromIme=true)
D/EGL_emulation: app_time_stats: avg=273.66ms min=15.43ms max=498.04ms count=4
D/InsetsController: show(ime(), fromIme=true)
D/EGL_emulation: app_time_stats: avg=127.14ms min=15.43ms max=268.64ms count=8
D/EGL_emulation: app_time_stats: avg=84.38ms min=3.27ms max=497.19ms count=11
D/EGL_emulation: app_time_stats: avg=328.67ms min=100.01ms max=500.65ms count=4
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10148; state: ENABLED
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.foodwaste, PID: 4879
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.foodwaste/com.example.foodwaste.MainPage}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2115)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1762)
        at android.app.Activity.startActivityForResult(Activity.java:5407)
        at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:597)
        at android.app.Activity.startActivityForResult(Activity.java:5365)
        at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:583)
        at android.app.Activity.startActivity(Activity.java:5751)
        at android.app.Activity.startActivity(Activity.java:5704)
        at com.example.foodwaste.LoginActivity.MainPageActivity(LoginActivity.java:36)
        at com.example.foodwaste.LoginActivity$1.onClick(LoginActivity.java:27)
        at android.view.View.performClick(View.java:7455)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
        at android.view.View.performClickInternal(View.java:7432)
        at android.view.View.access$3700(View.java:835)
        at android.view.View$PerformClick.run(View.java:28810)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7842)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

I forgot to Add My MainPage Activity to my AndroidManifest.xml

Found this in the logs -

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.foodwaste/com.example.foodwaste.MainPage}; have you declared this activity in your AndroidManifest.xml?

So I just had to add this to my AndroidManifest.xml -

<activity
            android:name=".MainPageActivity"
            android:exported="false" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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