ClassCastException:片段无法强制转换为Fragment

时间:2016-12-11 13:21:22

标签: java android android-fragments error-handling casting

我有这个应用程序,在MainActivity(这里是LoginActivity)中首先用片段(LoginFragment)替换,以获得良好的代码。 如果用户想要注册,则直接从mainActivity supportFragment manager重定向到新的SignUpFragment:

//setting the first fragment in onCreate
    fragmentManager = getSupportFragmentManager();
    LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);

    if(fragment == null){
        fragment = LoginFragment.newInstance();
        fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }

//Opening new registration fragment in LoginFragment.java
    signUpTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ((LoginActivity)getActivity()).loadSignUpFragment();
        }
    });


//In LoginActvity.java
public void loadSignUpFragment(){
    SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
    fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
一切都很好,正在开始工作。尝试注册新用户正在运行 但是,在应用了一些次要代码更改后(如果登录失败时显示小吃栏),我收到了错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.minimalart.studentlife/com.minimalart.studentlife.activities.LoginActivity}: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                  at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)
                  at android.app.ActivityThread.-wrap19(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
               Caused by: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
                  at com.minimalart.studentlife.activities.LoginActivity$override.onCreate(LoginActivity.java:38)
                  at com.minimalart.studentlife.activities.LoginActivity$override.access$dispatch(LoginActivity.java)
                  at com.minimalart.studentlife.activities.LoginActivity.onCreate(LoginActivity.java:0)
                  at android.app.Activity.performCreate(Activity.java:6679)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                  at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
                  at android.app.ActivityThread.-wrap19(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6119) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

为什么我这样做? 我只是从我的主要活动中切换和打开片段

感谢。

所有LoginActivity.java:

package com.minimalart.studentlife.activities;

import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

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.minimalart.studentlife.R;
import com.minimalart.studentlife.fragments.LoginFragment;
import com.minimalart.studentlife.fragments.SignUpFragment;


public class LoginActivity extends AppCompatActivity {

    private FragmentManager fragmentManager;
    private FirebaseAuth firebaseAuth;


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

        firebaseAuth = FirebaseAuth.getInstance();
        fragmentManager = getSupportFragmentManager();
        LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);

        if(fragment == null){
            fragment = LoginFragment.newInstance();
            fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
        }

    }

    public void loadSignUpFragment(){
        SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
        fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
    }

    public void signUpNewUser(String email, String pass, String firstName, String secName, String age){
        firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){

                }
                else{
                    Snackbar.make(findViewById(R.id.signUpLinearLayout), task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
                }

                // ...
            }
        });
    }

    public void logInUser(String email, String pass){

    }

}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,我发现问题在于声明主片段

替换

LoginFragment fragment = (LoginFragment)fragmentManager.findFragmentById(R.id.activity_main_content);

Fragment fragment = fragmentManager.findFragmentById(R.id.activity_main_content);

感谢@Selvin提示:)