当前位置: 首页 > 知识库问答 >
问题:

Android.Widget.Toolbar不能强制转换为AndroidX.AppCompat.Widget.Toolbar

梁丘波
2023-03-14

当单击按钮时,应用程序崩溃,并且是基于logcat错误的gradle文件中的任何问题。

以下是logcat错误

2020-07-25 11:58:56.040 11494-11620/com.example.dotchat E/ActivityThread: Failed to find provider info for cn.teddymobile.free.anteater.den.provider
2020-07-25 11:58:56.903 11494-11569/com.example.dotchat E/Parcel: Reading a NULL string not supported here.
2020-07-25 11:58:57.356 11494-11494/com.example.dotchat E/Parcel: Reading a NULL string not supported here.
2020-07-25 11:58:58.761 11494-11494/com.example.dotchat E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dotchat, PID: 11494
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dotchat/com.example.dotchat.LoginActivity}: java.lang.ClassCastException: android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2955)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3033)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1747)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:200)
        at android.app.ActivityThread.main(ActivityThread.java:6971)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassCastException: android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar
        at com.example.dotchat.LoginActivity.onCreate(LoginActivity.java:35)
        at android.app.Activity.performCreate(Activity.java:7225)
        at android.app.Activity.performCreate(Activity.java:7216)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3033) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1747) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:200) 
        at android.app.ActivityThread.main(ActivityThread.java:6971) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

这是我的RegisterActivity.java文件

package com.example.dotchat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;
import java.util.Objects;

public class RegisterActivity extends AppCompatActivity {

    EditText username, email, password;
    Button btn_register;

    FirebaseAuth auth;
    DatabaseReference reference;

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

       Toolbar toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        


        username=findViewById(R.id.username);
        email=findViewById(R.id.email);
        password=findViewById(R.id.password);
        btn_register=findViewById(R.id.btn_register);

        auth=FirebaseAuth.getInstance();

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt_username =username.getText().toString();
                String txt_email =email.getText().toString();
                String txt_password =password.getText().toString();

                if (TextUtils.isEmpty(txt_username) ||TextUtils.isEmpty(txt_email) ||TextUtils.isEmpty(txt_password)){
                    Toast.makeText(RegisterActivity.this,"All fields are required!",Toast.LENGTH_SHORT).show();
                } else if (txt_password.length()<8){
                    Toast.makeText(RegisterActivity.this,"Password must be atleast 8 characters!",Toast.LENGTH_SHORT).show();
                } else {
                    register(txt_username,txt_email,txt_password);
                }
            }
        });
    }

    private void register(final String username, String email, String password){

        auth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isComplete()) {
                            FirebaseUser firebaseUser = auth.getCurrentUser();
                            assert firebaseUser != null;
                            String userid = firebaseUser.getUid();

                            reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

                            HashMap<String,String> hashMap=new HashMap<>();
                            hashMap.put("id",userid);
                            hashMap.put("username",username);
                            hashMap.put("imageURL","default");

                            reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()){
                                        Intent intent=new Intent(RegisterActivity.this,MainActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                        finish();
                                    }

                                }
                            });
                        } else {
                            Toast.makeText(RegisterActivity.this,"Sorry! You can't register with this email or password",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}

这是loginactivity.java文件

package com.example.dotchat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

import java.util.Objects;

//import android.widget.Toolbar

public class LoginActivity extends AppCompatActivity {

    EditText  email,password;
    Button btn_login;

    FirebaseAuth auth;

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


       Toolbar toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        auth=FirebaseAuth.getInstance();

        email=findViewById(R.id.email);
        password=findViewById(R.id.password);
        btn_login=findViewById(R.id.btn_login);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt_email=email.getText().toString();
                String txt_password=password.getText().toString();

                if(TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)){
                    Toast.makeText(LoginActivity.this,"All fields are required",Toast.LENGTH_SHORT).show();
                } else {
                    auth.signInWithEmailAndPassword(txt_email,txt_password)
                            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()){
                                        Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        Toast.makeText(LoginActivity.this,"Authentication failed",Toast.LENGTH_SHORT).show();
                                    }

                                }
                            });
                }
            }
        });

    }
}

这是bar_layout.xml文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:background="#79D0D1D0"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/MenuStyle">

</androidx.appcompat.widget.Toolbar>

这是gradle文件

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.dotchat"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'com.google.firebase:firebase-auth:19.3.2'
    implementation 'com.google.firebase:firebase-database:19.3.1'
    implementation 'com.google.firebase:firebase-core:17.4.4'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

这是activity_login.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:orientation="vertical"
    android:background="@drawable/appbackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">


    <ImageView
        android:layout_width="145dp"
        android:layout_height="131dp"
        android:layout_gravity="center"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="50dp"
        android:src="@drawable/logotblack1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="35dp"
        android:layout_marginLeft="275dp"
        android:layout_marginTop="133dp"
        android:text="C h a t"
        android:textSize="20dp"
        android:textColor="#000" />

    <include
        android:id="@+id/toolbar"
        layout="@layout/bar_layout"
        android:layout_width="match_parent"
        android:layout_height="37dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar"
        android:layout_marginTop="224dp"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="16dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="35dp"
            android:text="Login into your Account"
            android:textColor="#000"
            android:textSize="20dp"
            />

        <EditText
            android:id="@+id/email"
            android:layout_width="378dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_round"
            android:drawableRight="@drawable/gmail"
            android:hint="                                       Email"
            android:textColorHint="#fff"
            android:inputType="textEmailAddress" />

        <EditText
            android:id="@+id/password"
            android:layout_width="378dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_round"
            android:drawableRight="@drawable/psw"
            android:ems="10"
            android:hint="                                    Password"
            android:textColorHint="#fff"
            android:inputType="textPassword" />

        <Button
            android:id="@+id/btn_login"
            android:layout_width="125dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:background="@drawable/button_roundl"
            android:text="Login"
            android:textColor="#000" />

    </LinearLayout>

</RelativeLayout>

这是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="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#fff"
            android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/MenuStyle">

            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:id="@+id/profile_image"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Username"
                android:textColor="#000"
                android:textStyle="bold"
                android:layout_marginStart="25dp"/>

        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>

</LinearLayout>

这是activity_register.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:orientation="vertical"
    android:background="@drawable/appbackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RegisterActivity">


    <ImageView
        android:layout_width="115dp"
        android:layout_height="110dp"
        android:layout_gravity="center"
        android:layout_marginLeft="90dp"
        android:layout_marginTop="100dp"
        android:src="@drawable/logotblack1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="200dp"
        android:layout_marginTop="153dp"
        android:paddingBottom="35dp"
        android:text="C h a t"
        android:textColor="#000"
        android:textSize="30dp" />

    <include
        android:id="@+id/toolbar"
        layout="@layout/bar_layout"
        android:layout_width="match_parent"
        android:layout_height="37dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar"
        android:layout_marginTop="278dp"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="16dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="35dp"
            android:text="Create a New Account"
            android:textColor="#000"
            android:textSize="25dp"
            android:textStyle="bold" />

        <EditText

            android:id="@+id/username"
            android:layout_width="279dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_round"
            android:drawableRight="@drawable/usericon"
            android:hint="                      Username"
            android:textColorHint="#fff"/>

        <EditText
            android:id="@+id/email"
            android:layout_width="278dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_round"
            android:drawableRight="@drawable/gmail"
            android:hint="                          Email"
            android:inputType="textEmailAddress"
            android:textColorHint="#fff"/>

        <EditText
            android:id="@+id/password"
            android:layout_width="278dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_round"
            android:drawableRight="@drawable/psw"
            android:ems="10"
            android:hint="                       Password"
            android:inputType="textPassword"
            android:textColorHint="#fff"/>

        <Button
            android:layout_width="176dp"
            android:layout_height="wrap_content"
            android:id="@+id/btn_register"
            android:layout_marginTop="25dp"
            android:background="@drawable/button_round"
            android:text="register now"
            android:textColor="#000" />

    </LinearLayout>

</RelativeLayout>

这是activity_start.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/appbackground"
    tools:context=".StartActivity">
    <ImageView
        android:layout_width="131dp"
        android:layout_height="110dp"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="295dp"
        android:src="@drawable/logotblack1" />

    <ImageView
        android:layout_width="181dp"
        android:layout_height="147dp"
        android:layout_marginLeft="200dp"
        android:layout_marginRight="75dp"
        android:layout_marginTop="299dp"
        android:src="@drawable/chatblack" />




        <Button
            android:id="@+id/login"
            android:layout_width="125dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="650dp"
            android:layout_marginLeft="20dp"
            android:background="@drawable/llogin"
            android:text="Login"
            android:textColor="#000" />

        <Button
            android:id="@+id/register"
            android:layout_width="176dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="650dp"
            android:layout_marginLeft="193dp"
            android:background="@drawable/llogin"
            android:text="register now"
            android:textColor="#000" />

</RelativeLayout>

共有1个答案

萧鸿轩
2023-03-14

xml文件中定义的工具栏类错误。更改自

<工具栏.../>

在您的XML中,您可能使用声明了您的工具栏。在这种情况下,工具栏将从包android.widget创建。因此,如果您试图通过将findViewById转换为AndroidX.AppCompat.Widget.Toolbar来调用它,它肯定会抛出一个RuntimeException。

如果您使用的是AndroidX,那么您必须将工具栏的xml声明更改为

然后,您可以继续调用您的(AndroidX.AppCompat.Widget.Toolbar)findViewByid(..)这应该会成功

 类似资料: