Search code examples
javaandroidandroid-fragmentactivity

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{.UpdateProfileFragment cannot be cast to android.app.Activity


I'm having this error after clicking button in my AccountFragment

public class AccountFragment extends Fragment  {
    private static final String TAG = "Profile" ;
    FirebaseAuth firebaseAuth;
    FirebaseUser currentUser;
    DatabaseReference databaseReference;
    TextView tv_name, tv_email, tv_gender, tv_home, tv_phone;
    private String userID;
    Button btn_update;



    public AccountFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_account, container, false);

        tv_name=view.findViewById(R.id.tv_name);
        tv_email=view.findViewById(R.id.tv_email);
        tv_gender=view.findViewById(R.id.tv_gender);
        tv_home=view.findViewById(R.id.tv_home);
        tv_phone=view.findViewById(R.id.tv_phone);
        btn_update=view.findViewById(R.id.btn_update);


        //ini
        firebaseAuth = FirebaseAuth.getInstance();
        currentUser = firebaseAuth.getCurrentUser();
        userID = currentUser.getUid();
        databaseReference = FirebaseDatabase.getInstance().getReference("Customer").child(firebaseAuth.getUid());

        //For Retrieve Information
        databaseReference.addValueEventListener(new ValueEventListener() {


            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Log.d( TAG, "onDataChange :" +dataSnapshot);

                    Customer cust = dataSnapshot.getValue(Customer.class);
                    tv_name.setText(cust.getName());
                    tv_email.setText(cust.getEmail());
                    tv_gender.setText(cust.getGender());
                    tv_home.setText(cust.getHome_address());
                    tv_phone.setText(cust.getTelephone_number());

            }

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

            }
        });

        //For Update Method

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

        return view;
    }

    // For update and pass information method
    private void openUpdateProfile() {


        Intent intent= new Intent(getActivity(), UpdateProfileFragment.class);

        //pass value from current to next page
        intent.putExtra("name",tv_name.getText().toString().trim());
        intent.putExtra("email", tv_email.getText().toString().trim());
        intent.putExtra("Home Address",tv_home.getText().toString().trim());
        intent.putExtra("Telephone", tv_phone.getText().toString().trim());
        startActivity(intent);

    }

after clicking the button i got this error 2019-09-22 22:20:32.757 6631-6631/com.example.g E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.g, PID: 6631 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.g/com.example.g.UpdateProfileFragment}: java.lang.ClassCastException: com.example.g.UpdateProfileFragment cannot be cast to android.app.Activity at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.ClassCastException: com.example.gerobokgo.UpdateProfileFragment cannot be cast to android.app.Activity at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69) at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41) at android.app.Instrumentation.newActivity(Instrumentation.java:1215) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:193)  at android.app.ActivityThread.main(ActivityThread.java:6669)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

UpdateProfileFragment

public class UpdateProfileFragment extends Fragment implements View.OnClickListener {
    EditText tv_name, tv_email, tv_home, tv_phone;
    Button btn_update;

    FirebaseAuth firebaseAuth;
    FirebaseUser currentUser;
    DatabaseReference databaseReference;


    public UpdateProfileFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_update_profile, container, false);


        //get data from intert (data from previous page)

        Intent intent = getActivity().getIntent();
        String name = intent.getStringExtra("Name");
        String email = intent.getStringExtra("Email");
        String address = intent.getStringExtra(" Shipping Address");
        String phone = intent.getStringExtra("Telephone Number");

        //ini
        firebaseAuth = FirebaseAuth.getInstance();
        currentUser = firebaseAuth.getCurrentUser();
        databaseReference = FirebaseDatabase.getInstance().getReference("Customer").child(firebaseAuth.getUid());

        tv_name = view.findViewById(R.id.tv_name);
        tv_email = view.findViewById(R.id.tv_email);
        tv_home = view.findViewById(R.id.tv_home);
        tv_phone = view.findViewById(R.id.tv_phone);

        tv_name.setText(name);
        tv_email.setText(email);
        tv_home.setText(address);
        tv_phone.setText(phone);

        btn_update.setOnClickListener(this);


        return view;
    }

    @Override
    public void onClick(View view) {

    }

    private void updateProfile() {
        Intent intent = getActivity().getIntent();

        String userUid = firebaseAuth.getCurrentUser().getUid();
        String name = tv_name.getText().toString().trim();
        String email = tv_email.getText().toString().trim();
        String home = tv_home.getText().toString().trim();
        String phone = tv_phone.getText().toString().trim();

        Customer cust = new Customer(userUid, name, email, home, phone);
        databaseReference.child("Customer").child(userUid).setValue(cust).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(getActivity(), "Update Successfully", Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                    startActivity(new Intent(getActivity(), AccountFragment.class));


                }
            }
        });
    }
}

Solution

  • You can't open fragment using startActivity, you need to implement a callback which triggers when your user's profile has updated successfully. In your host activity make an interface as follows :

    public interface UpdateProfileSuccess{
        void presentAccountFragment();
    }
    

    Also instantiate that in activity as:

    UpdateProfileSuccess callback = new UpdateProfileSuccess(){
    @Override
    void presentAccountFragment(){
    getSupportFragmentManager().beginTransaction().replace(R.id.container,new 
            AccuontFragment()).commit();
        }
    }
    

    In your update profile fragment make a constructor taking that callback as :

    private MainActivity.UpdateProfileSuccess callback;
    public UpdateProfileFragment(MainActivity.UpdateProfileSuccess callback){
        this.callback = callback;
    }
    

    Finally in onComplete of your request consume that callback as:

    callback.presentAccountFragment();
    

    This way your activity will be responsible of presenting AccountFragment.