简体   繁体   中英

android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar

Applicaton crashes when click on the button and is the any problem in thne gradle file based on the logcat error.

Following is the logcat error

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) 

This is my Registeractivity.java file

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();
                        }
                    }
                });
    }
}

This is LoginActivity.java file

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();
                                    }

                                }
                            });
                }
            }
        });

    }
}

This is bar_layout.xml file

<?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>

This is gradle file

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'

}

This is the activity_login.xml file

<?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>

This is activity_main.xml file

<?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>

This is activity_register.xml file

<?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>

This is activity_start.xml file

<?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>

Wrong Toolbar class defined in your xml file. Change it from

<Toolbar.../>

to

<androidx.appcompat.widget.Toolbar.../>

In your XML, you probably declared your toolbar using just in that case, the toolbar will be created from the package android.widget. So if you try to call findViewById by casting it to androidx.appcompat.widget.Toolbar it will surely throw you a RuntimeException.

If you are using AndroidX, which you should, then you have to change the xml declaration of your toolbar to <androidx.appcompat.widget.Toolbar></androidx.appcompat.widget.Toolbar>

You can then proceed to call your (androidx.appcompat.widget.Toolbar) findViewByid(..) which should succeed

In the bar_layout file, I think you have put the wrong popup menu style that is not defined in android.

For this, you have to create a MenuStyle attribute in style folder, then you code run perfectly.

<style name="MenuStyle" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <!--  Write your attributes here -->
</style>

or you can prefer other style attributes that are pre-defined in android.

Hope it helps ).

Just came across the same issue. Besides following Moaz Ragab answer, I'd also suggest to check AndroidManifest.xml file and make sure you have android:theme="@style/AppTheme.NoActionBar" for the corresponding activity, which, in your case, is LoginActivity.

For example:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dotchat">
    <application>
        <activity
            android:name=".LoginActivity"
            android:label="@string/activity_login"
            android:theme="@style/AppTheme.NoActionBar" />
    </application>
</manifest>

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