我无法在Recyclerview项目中打开片段

时间:2018-09-07 14:22:51

标签: android android-recyclerview

我在打开来自recyclerview项目的片段时遇到问题。当我单击项目内的按钮时,我收到错误消息:在空对象引用上出现onEditClick(com.example.taskapprealm.edit.EditFragment)'。 Null在适配器内部。

MainActivity内部的方法:

 @Override
public void onEditClick(EditFragment editFragment) {
    Fragment fragment = new EditFragment();

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.recycler_view, fragment);
    transaction.addToBackStack(null);
    transaction.commit();

}

和适配器中的onBindViewHolder:

 @Override
public void onBindViewHolder(@NonNull final TaskViewHolder holder, @SuppressLint("RecyclerView") final int position) {
   Task task = tasks.get(position);
   holder.textItem.setText(task.getText());
   holder.dateItem.setText(task.getDate());
   holder.timeItem.setText(task.getTime());
   holder.deleteButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           int position = holder.getAdapterPosition();
           Log.d(TAG, "DELETE_CLICK " + holder.getAdapterPosition());
           callback.onDeleteClick(position);
           notifyItemRemoved(holder.getAdapterPosition());
       }

   });


   holder.editButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           Toast.makeText(v.getContext(), "TEST " + holder.getAdapterPosition(), Toast.LENGTH_LONG).show();

           mainActivity.onEditClick(editFragment);
       }
   });

}

接口:

 void onEditClick(EditFragment editFragment);

日志:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.taskapprealm.debug, PID: 8045
              java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.taskapprealm.main.MainActivity.onEditClick(com.example.taskapprealm.edit.EditFragment)' on a null object reference
                  at com.example.taskapprealm.main.MainAdapter$2.onClick(MainAdapter.java:94)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

似乎您在引用RecyclerView而不是Fragment容器,

transaction.replace(R.id.recycler_view, fragment);

可能recycler_view应该用您的Fragment容器替换。另外,请检查EditFragment视图是否正确,并且没有被onCreateView()方法中的任何错误或错字所取代。

此外,如上所述,mainActivity看起来为空。

阅读: How to get a context in a recycler view adapter