Приложение продолжает падать каждый раз, когда я нажимаю кнопку входа - PullRequest
0 голосов
/ 02 апреля 2020

Я новичок в android, я следовал некоторому руководству, и в этот момент приложение продолжает падать, когда я нажимаю кнопку входа в систему. Когда я запускаю приложение и нажимаю кнопку входа в систему, приложение вылетает и в logcat появляется эта ошибка java RuntimeException. Это мой logcat, loginacctivity. xml и loginactivity. java.

java .lang.RuntimeException: Невозможно запустить действие ComponentInfo {com.example.ugtunda / com.example. ugtunda.LoginActivity}: java .lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView нельзя преобразовать в com.rey.material.widget.TextView в android .app.ActivityThread.performLaunchActivity (ActivityThread. * 1019: 2806) на android .app.ActivityThread.handleLaunchActivity (ActivityThread. java: 2884) на android .app.ActivityThread.-wrap11 (неизвестный источник: 0) на android .app.ActivityThread $ H.handleMessage (ActivityThread. java: 1614) в android .os.Handler.dispatchMessage (Обработчик. java: 106) в android .os.Looper.l oop (Looper. java: 164) в android .app.ActivityThread.main (ActivityThread. java: 6524) в java .lang.reflect.Method.invoke (собственный метод) в com. android .internal.os.RuntimeInit $ MethodAndArgsCaller. Выполнить (RuntimeInit. java: 451) на com. android .internal.os.ZygoteInit.main (ZygoteInit. java: 888). Причина: : java .lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView не может быть приведен к com.rey.material.widget.TextView на com.example.ugtunda.LoginActivity.onCreate (LoginActivity. java: 48) в android .app.Activity.performCreate (Activity. java: 7044) в android .app.Activity.performCreate (Activity. java: 7035) в android .app.Instrumentation.callActivityOnCreate (Instrumentation. java: 1214) в android .app.ActivityThread.performLaunchActivity (ActivityThread. java: 2759)

Вот мой логин_активности_ 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/login"
    tools:context=".LoginActivity">

    <ImageView
        android:id="@+id/login_applogo"
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:src="@drawable/applogo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200dp"
        />


    <EditText
        android:id="@+id/login_phone_number_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/login_applogo"
        android:background="@drawable/input_design"
        android:padding="20dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:hint="Phone Number"
        android:inputType="number"
        android:textColor="@color/colorPrimaryDark"
        android:textColorHint="@color/colorPrimaryDark"
        android:textSize="17sp"
        android:textStyle="bold"
        />


    <EditText
        android:id="@+id/login_password_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/login_phone_number_input"
        android:background="@drawable/input_design"
        android:padding="20dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="6dp"
        android:hint="Password"
        android:inputType="textPassword"
        android:textColor="@color/colorPrimaryDark"
        android:textColorHint="@color/colorPrimaryDark"
        android:textSize="17sp"
        android:textStyle="bold"
        />

    <LinearLayout
        android:id="@+id/linear_layout_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/login_password_input"
        android:layout_marginTop="5dp"
        >

        <com.rey.material.widget.CheckBox
            android:id="@+id/remember_me_chkb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Material.Drawable.CheckBox"
            android:text="Remember Me"
            android:textColor="@color/colorPrimaryDark"
            app:cbd_strokeColor="@color/colorPrimaryDark"
            android:gravity="center_vertical"
            android:textSize="16sp"
            android:textStyle="bold"
            android:layout_marginLeft="17dp"

            />


        <TextView
            android:id="@+id/forget_password_link"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Forget Password"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_marginLeft="80dp"
            />
    </LinearLayout>


    <Button
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linear_layout_1"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:background="@drawable/buttons"
        android:padding="17dp"
        android:text="Login"
        android:textAllCaps="false"
        android:textColor="@android:color/white"
        android:textSize="18sp" />


    <TextView
        android:id="@+id/admin_panel_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/login_button"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="80dp"
        android:layout_marginEnd="23dp"
        android:text="I'm an Admin"
        android:textAppearance="@android:style/TextAppearance.Material.Small"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/not_admin_panel_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm not an Admin"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/login_button"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginLeft="80dp"
        android:layout_marginEnd="23dp"
        android:layout_marginStart="25dp"
        android:visibility="invisible"
        />

</RelativeLayout>

И наконец, мой логин. java

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

import android.app.ProgressDialog;
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 com.example.ugtunda.Models.Users;
import com.example.ugtunda.Prevalent.Prevalent;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rey.material.widget.CheckBox;
import com.rey.material.widget.TextView;

import io.paperdb.Paper;

public class LoginActivity extends AppCompatActivity
{
    private EditText InputPhoneNumber, InputPassword;
    private Button LoginButton;
    private ProgressDialog loadingBar;
    private TextView AdminLink, NotAdminLink;

    private String parentDbName = "Users";
    private CheckBox chkBoxRememberMe;


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


        LoginButton = findViewById(R.id.login_button);
        InputPassword = findViewById(R.id.login_password_input);
        InputPhoneNumber = findViewById(R.id.login_phone_number_input);
        AdminLink = findViewById(R.id.admin_panel_link);
        NotAdminLink = findViewById(R.id.not_admin_panel_link);
        loadingBar = new ProgressDialog(this);


        chkBoxRememberMe = findViewById(R.id.remember_me_chkb);
        Paper.init(this);


        LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                LoginUser();
            }
        });

        AdminLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                LoginButton.setText("Login Admin");
                AdminLink.setVisibility(View.INVISIBLE);
                NotAdminLink.setVisibility(View.VISIBLE);
                parentDbName = "Admins";
            }
        });

        NotAdminLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                LoginButton.setText("Login");
                AdminLink.setVisibility(View.VISIBLE);
                NotAdminLink.setVisibility(View.INVISIBLE);
                parentDbName = "Users";
            }
        });
    }



    private void LoginUser()
    {
        String phone = InputPhoneNumber.getText().toString();
        String password = InputPassword.getText().toString();

        if (TextUtils.isEmpty(phone))
        {
            Toast.makeText(this, "Please write your phone number...", Toast.LENGTH_SHORT).show();
        }
        else if (TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "Please write your password...", Toast.LENGTH_SHORT).show();
        }
        else
        {
            loadingBar.setTitle("Login Account");
            loadingBar.setMessage("Please wait, while we are checking the credentials.");
            loadingBar.setCanceledOnTouchOutside(false);
            loadingBar.show();


            AllowAccessToAccount(phone, password);
        }
    }



    private void AllowAccessToAccount(final String phone, final String password)
    {
        if(chkBoxRememberMe.isChecked())
        {
            Paper.book().write(Prevalent.USER_PHONE_KEY, phone);
            Paper.book().write(Prevalent.USER_PASSWORD_KEY, password);
        }


        final DatabaseReference RootRef;
        RootRef = FirebaseDatabase.getInstance().getReference();


        RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                if (dataSnapshot.child(parentDbName).child(phone).exists())
                {
                    Users usersData = dataSnapshot.child(parentDbName).child(phone).getValue(Users.class);

                    if (usersData.getPhone().equals(phone))
                    {
                        if (usersData.getPassword().equals(password))
                        {
                            if (parentDbName.equals("Admins"))
                            {
                                Toast.makeText(LoginActivity.this, "Welcome Admin, you are logged in Successfully...", Toast.LENGTH_SHORT).show();
                                loadingBar.dismiss();

                                Intent intent = new Intent(LoginActivity.this, AdminCategoryActivity.class);
                                startActivity(intent);
                            }
                            else if (parentDbName.equals("Users"))
                            {
                                Toast.makeText(LoginActivity.this, "logged in Successfully...", Toast.LENGTH_SHORT).show();
                                loadingBar.dismiss();

                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                Prevalent.currentOnlineUser = usersData;
                                startActivity(intent);
                            }
                        }
                        else
                        {
                            loadingBar.dismiss();
                            Toast.makeText(LoginActivity.this, "Password is incorrect.", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                else
                {
                    Toast.makeText(LoginActivity.this, "Account with this " + phone + " number do not exists.", Toast.LENGTH_SHORT).show();
                    loadingBar.dismiss();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

Ответы [ 4 ]

2 голосов
/ 02 апреля 2020

Похоже, что вы определяете стандартные компоненты Android в макете XML, а затем пытаетесь раздувать их в пользовательские компоненты (пакет com.rey.material). Попробуйте перейти к импорту и удалить строки com.rey.material. Затем, когда ваша IDE предложит вам импортировать TextView и Checkbox, убедитесь, что вы импортируете версии из android.widget, а не com.rey.material. Кроме того, вы можете изменить файл XML, указав компоненты com.rey.material, если хотите использовать их вместо компонентов по умолчанию.

2 голосов
/ 02 апреля 2020

Вам необходимо заменить

import com.rey.material.widget.TextView;

на

import android.widget.TextView;

.

ИЛИ

.

Заменить

<TextView
            android:id="@+id/forget_password_link"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Forget Password"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_marginLeft="80dp"
            />

с

<com.rey.material.widget.TextView
            android:id="@+id/forget_password_link"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Forget Password"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="15sp"
            android:textStyle="bold"
            android:layout_marginLeft="80dp" />

в вашем xml файле

0 голосов
/ 02 апреля 2020

Похоже, вы используете кнопку AppCompat в своем XML, но используете кнопку материала в своем коде java.

Так что они должны быть одинаковыми.

Сначала вам нужно использовать правильный импорт для любого вида, который вы используете, если вы хотите использовать кнопку AppCompat, то импортировать так:

import android.widget.Button;

Если вы хотите использовать кнопку Материал, то используйте этот импорт:

import com.rey.material.widget.Button;

То же самое относится и к TextView.

Надеюсь, это поможет!

0 голосов
/ 02 апреля 2020

androidx.appcompat.widget.AppCompatTextView не может быть приведен к com.rey.material.widget.TextView

В вашем xml вы используете SDK TextView, но в ваш код, вы хотите com.rey.material.widget один.

-> Изменить один из этих

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...