提问者:小点点

Android应用程序在尝试打开片段时崩溃


我创建了一个词汇表应用程序,用户可以在其中添加他们的单词。我使用Firebase进行单词存储。该应用程序一开始运行良好,但我试图改进该片段中的一些内容,结果它开始崩溃。我删除了我添加的所有内容,但当我尝试打开该片段时,它仍然会崩溃。在运行中,我也无法弄清楚任何事情。

这是那个片段的代码

公共类MyWordsFragment扩展Fragment{

private FloatingActionButton mUp,mLogout,mAdd;
private Animation FabOpen, FabClose, FabClockwise, FabAntiClockwise;
boolean isOpen = false;

private FirebaseAuth mAuth;
private DatabaseReference mFirebase;

private RecyclerView mMyWordsRecyclerView;

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


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

    return mainView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mUp = (FloatingActionButton) getActivity().findViewById(R.id.myword_fab_up);
    mLogout = (FloatingActionButton) getActivity().findViewById(R.id.myword_fab_logout);
    mLogout.setBackgroundTintList(ColorStateList.valueOf(Color
            .parseColor("#212121")));
    mAdd = (FloatingActionButton) getActivity().findViewById(R.id.myword_fab_add);
    mAdd.setBackgroundTintList(ColorStateList.valueOf(Color
            .parseColor("#212121")));

    FabOpen = AnimationUtils.loadAnimation(getContext(),R.anim.fab_open);
    FabClose = AnimationUtils.loadAnimation(getContext(),R.anim.fab_close);
    FabClockwise = AnimationUtils.loadAnimation(getContext(),R.anim.rotate_clockwise);
    FabAntiClockwise = AnimationUtils.loadAnimation(getContext(),R.anim.rotate_anticlockwise);

    mAuth = FirebaseAuth.getInstance();

    FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();
    String uid = currentuser.getUid();

    mFirebase = FirebaseDatabase.getInstance().getReference().child("MyWords").child(uid);
    mFirebase.keepSynced(true);

    mMyWordsRecyclerView = (RecyclerView)getActivity().findViewById(R.id.myword_category_rv);
    mMyWordsRecyclerView.setHasFixedSize(true);
    mMyWordsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    mAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final AlertDialog.Builder mBulider = new AlertDialog.Builder(getActivity());
            View mView = getLayoutInflater().inflate(R.layout.add_category_dialog,null);

            final TextInputLayout mCategory = (TextInputLayout)mView.findViewById(R.id.add_categoryName);
            final TextInputLayout mWord = (TextInputLayout)mView.findViewById(R.id.add_firstword);
            final TextInputLayout mMeaning = (TextInputLayout)mView.findViewById(R.id.add_firstmeaning);

            mBulider.setView(view)
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    })
                    .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            String category = mCategory.getEditText().getText().toString();
                            String word = mWord.getEditText().getText().toString();
                            String meaning = mMeaning.getEditText().getText().toString();

                            if(!TextUtils.isEmpty(category) && !TextUtils.isEmpty(word) && !TextUtils.isEmpty(meaning)){

                                HashMap<String, String> addcat = new HashMap<>();
                                addcat.put("dbWord",word);
                                addcat.put("dbMeaning",meaning);

                                mFirebase.child(category).push().setValue(addcat).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()){
                                            Toast.makeText(getActivity(),"Category is Added",Toast.LENGTH_LONG).show();
                                        }else {
                                            Toast.makeText(getActivity(),task.getException().getMessage(),Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                                mFirebase.keepSynced(true);

                                dialogInterface.dismiss();
                            }else {
                                Toast.makeText(getActivity(),"Fill all the fields and try again",Toast.LENGTH_LONG).show();
                            }
                        }
                    });

            mBulider.setView(mView);
            AlertDialog dialog = mBulider.create();
            dialog.show();
        }
    });

    mUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (isOpen){

                mLogout.startAnimation(FabClose);
                mAdd.startAnimation(FabClose);
                mUp.startAnimation(FabAntiClockwise);
                mLogout.setClickable(false);
                mAdd.setClickable(false);
                isOpen = false;

            }else {

                mLogout.startAnimation(FabOpen);
                mAdd.startAnimation(FabOpen);
                mUp.startAnimation(FabClockwise);
                mLogout.setClickable(true);
                mAdd.setClickable(true);
                isOpen = true;
            }

        }
    });

    mLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // 1. Instantiate an AlertDialog.Builder with its constructor
            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            // 2. Chain together various setter methods to set the dialog characteristics
            builder.setMessage("Are you sure you want to logout?")
                    .setTitle("Logout");

            // 3. Add the buttons
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User clicked YES button

                    mAuth.signOut();
                    Intent intent = new Intent(getActivity(),MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    getActivity().finish();
                }
            });
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                    dialog.cancel();

                }
            });

            // 4. Get the AlertDialog from create()
            AlertDialog dialog = builder.create();
            dialog.show();

        }
    });

}

@Override
public void onStart() {
    super.onStart();

    final FirebaseRecyclerAdapter<MyWordsCategoryModel, MyWordsCategoryViewholder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<MyWordsCategoryModel, MyWordsCategoryViewholder>(

            MyWordsCategoryModel.class,
            R.layout.mywords_rv_layout,
            MyWordsCategoryViewholder.class,
            mFirebase

    ) {
        @Override
        protected void populateViewHolder(MyWordsCategoryViewholder viewHolder, MyWordsCategoryModel model, int position) {

            final String dbcategoryId = getRef(position).getKey();
            viewHolder.setCategory(dbcategoryId);

            viewHolder.mCategoryDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // 1. Instantiate an AlertDialog.Builder with its constructor
                    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                    // 2. Chain together various setter methods to set the dialog characteristics
                    builder.setMessage("Are you sure you want to delete this category?")
                            .setTitle("Delete Category");

                    // 3. Add the buttons
                    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User clicked YES button

                            // 1. Instantiate an AlertDialog.Builder with its constructor
                            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                            // 2. Chain together various setter methods to set the dialog characteristics
                            builder.setMessage("All the words inside this category will be deleted")
                                    .setTitle("Delete All Words");

                            // 3. Add the buttons
                            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // User clicked YES button

                                    mFirebase.child(dbcategoryId).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(getActivity(),"Deleted",Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    });

                                }
                            });
                            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // User cancelled the dialog
                                    dialog.cancel();

                                }
                            });

                            // 4. Get the AlertDialog from create()
                            AlertDialog dialogfinal = builder.create();
                            dialogfinal.show();

                        }
                    });
                    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                            dialog.cancel();

                        }
                    });

                    // 4. Get the AlertDialog from create()
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            });


            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                        Intent profileIntant = new Intent(getActivity(), MyWordsListActivity.class);
                        profileIntant.putExtra("DbCategoryId", dbcategoryId);
                        startActivity(profileIntant);

                }
            });

        }
    };

    ScaleInAnimationAdapter alphaAdapter = new ScaleInAnimationAdapter(firebaseRecyclerAdapter);
    alphaAdapter.setDuration(800);
    alphaAdapter.setInterpolator(new OvershootInterpolator());
    alphaAdapter.setFirstOnly(false);

    mMyWordsRecyclerView.setAdapter(alphaAdapter);

}

public static class MyWordsCategoryViewholder extends RecyclerView.ViewHolder{

    View mView;
    public ImageView mCategoryDelete;

    public MyWordsCategoryViewholder(View itemView) {
        super(itemView);

        mView = itemView;

        mCategoryDelete = (ImageView)itemView.findViewById(R.id.mywords_rv_cross);

    }

    public void setCategory(String category){
        TextView cat = (TextView)mView.findViewById(R.id.mywords_rv_Category);
        cat.setText(category);
    }

}

}

错误运行

I/System.out: [socket][/10.163.173.254:38082] connected
D/NativeCrypto: ssl=0x80c12380 NativeCrypto_SSL_do_handshake               fd=0x8f732c60 shc=0x8f732c64 timeout_millis=0 client_mode=1 npn=0x0
D/NativeCrypto: ssl=0x80c12380 info_callback calling handshakeCompleted
D/skia: SkJpegCodec::onGetPixels +
D/skia: SkJpegCodec::onGetPixels -
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.aniketvishal.commonindianwords, PID: 7574
              com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.aniketvishal.commonindianwords.Models.MyWordsCategoryModel
                  at com.google.android.gms.internal.zg.zzb(Unknown Source)
                  at com.google.android.gms.internal.zg.zza(Unknown Source)
                  at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                  at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:22)
                  at com.firebase.ui.database.ObservableSnapshotArray.getObject(ObservableSnapshotArray.java:160)
                  at com.firebase.ui.database.CachingObservableSnapshotArray.getObject(CachingObservableSnapshotArray.java:40)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:180)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:217)
                  at jp.wasabeef.recyclerview.adapters.AnimationAdapter.onBindViewHolder(AnimationAdapter.java:54)
                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
                  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
                  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
                  at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
                  at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1710)
                  at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:346)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:910)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:712)
                  at android.view.Choreographer.doFrame(Choreographer.java:643)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:896)
                  at android.os.Handler.handleCallback(Handler.java:836)
                  at android.os.Handler.dispatchMessage(Handler.java:103)
                  at android.os.Looper.loop(Looper.java:203)
                  at android.app.ActivityThread.main(ActivityThread.java:6339)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1084)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:945)
D/OpenGLRenderer: ~CanvasContext() 0xa3afaa80
D/NativeCrypto: ssl=0x80c12380 cert_verify_callback => 1
D/NativeCrypto: ssl=0x80c12380 info_callback calling handshakeCompleted
D/NativeCrypto: ssl=0x80c12380 NativeCrypto_SSL_get_certificate => NULL
I/System.out: gba_cipher_suite:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
Application terminated.

请帮帮我谢谢


共1个答案

匿名用户

你正面临这个例外

DatabaseException: Can't convert object of type java.lang.String to type com.aniketvishal.commonindianwords.Models.MyWordsCategoryModel

因为您正在尝试读取类型的数据

ValueEventListener eventListener = new ValueEventListener() { 
@Override 
public void onDataChange(DataSnapshot dataSnapshot) {
  for(DataSnapshot ds : dataSnapshot.getChildren()) {
      MyWordsCategoryModel data = ds.getValue(MyWordsCategoryModel.class);
  }
}

有关详细信息,请查看此问题

数据库异常:无法将java. lang.String类型的对象转换为类型