在recyclerView中再次尝试setAdapter时出错

时间:2018-04-03 13:33:31

标签: java android android-recyclerview

我试图在用户删除他希望recyclelerView重新加载的项目之后这样做,所以一切看起来都很好,列表中的项目之间没有空格。但我一直在收到这个错误。会爱你的帮助。 每次错误都在setAdapter的行中时,任何想法是什么导致它?

public class mainScreen extends AppCompatActivity {
    Context context = mainScreen.this;
    ImageButton addButtonj;
    Intent intent;
    exercisesAdapter adapter;
    RecyclerView.Adapter mAdapter;
    ArrayList<Exercise> arrayList = new ArrayList();

    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
        addButtonj = (ImageButton) findViewById(R.id.addButton);


        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        arrayList = DBCommands.getExercise(context);

         adapter = new exercisesAdapter(mainScreen.this, arrayList);
        recyclerView.setAdapter(adapter);

        addButtonj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mainScreen.this, addingExercise.class);
                startActivity(intent);
            }
        });


        ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
                final int position = viewHolder.getAdapterPosition(); //get position which is swipe

                if (direction == ItemTouchHelper.LEFT) {    //if swipe left

                    AlertDialog.Builder builder = new AlertDialog.Builder(mainScreen.this); //alert for confirm to delete
                    builder.setMessage("Are you sure to delete?");    //set message

                    builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() { //when click on DELETE
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TextView theName = (TextView) viewHolder.itemView.findViewById(R.id.textView8);
                            String uID = theName.getText().toString();
//                            Toast.makeText(getApplicationContext(), "ID Value = " + uID + " Position = " + position, Toast.LENGTH_LONG).show();

                            DBCommands.deleteExercise(context, uID);
reload();
                        }
                    }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {  //not removing items if cancel is done
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mAdapter.notifyItemRemoved(position + 1);    //notifies the RecyclerView Adapter that data in mAdapter has been removed at a particular position.
                            mAdapter.notifyItemRangeChanged(position, mAdapter.getItemCount());   //notifies the RecyclerView Adapter that positions of element in mAdapter has been changed from position(removed element index to end of list), please update it.
                        }
                    }).show();  //show alert dialog

                }
            }


        };
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }

    public void reload(){
        arrayList = DBCommands.getExercise(context);
         adapter=new exercisesAdapter(this,arrayList);
**recyclerView.setAdapter(adapter);**
adapter.notifyDataSetChanged();

    }
}

和错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.enterprise.adirbenami.weight.mainScreen.reload(mainScreen.java:99)
    at com.enterprise.adirbenami.weight.mainScreen$2$2.onClick(mainScreen.java:78)
    at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

3 个答案:

答案 0 :(得分:1)

您已在活动中全局创建了RecyclerView个实例

但在onCreate()内,您获得了新实例RecyclerView

以便 recyclerView 全局为null

在java中称为Variable Shadowing

  

什么是变量阴影?

  • 当我们在闭包范围内定义变量时,会发生变量阴影,变量名称与我们已在外部范围中定义的变量的变量名称相同。
  • 换句话说,当局部变量与其中一个实例变量同名时,局部变量会影响方法块内的实例变量。

使用此

     recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

而不是

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

更改代码

public class mainScreen extends AppCompatActivity {
    Context context = mainScreen.this;
    ImageButton addButtonj;
    Intent intent;
    exercisesAdapter adapter;
    RecyclerView.Adapter mAdapter;
    ArrayList<Exercise> arrayList = new ArrayList();

    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
        addButtonj = (ImageButton) findViewById(R.id.addButton);


        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        arrayList = DBCommands.getExercise(context);

         adapter = new exercisesAdapter(mainScreen.this, arrayList);
        recyclerView.setAdapter(adapter);

        addButtonj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mainScreen.this, addingExercise.class);
                startActivity(intent);
            }
        });


        ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
                final int position = viewHolder.getAdapterPosition(); //get position which is swipe

                if (direction == ItemTouchHelper.LEFT) {    //if swipe left

                    AlertDialog.Builder builder = new AlertDialog.Builder(mainScreen.this); //alert for confirm to delete
                    builder.setMessage("Are you sure to delete?");    //set message

                    builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() { //when click on DELETE
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TextView theName = (TextView) viewHolder.itemView.findViewById(R.id.textView8);
                            String uID = theName.getText().toString();
//                            Toast.makeText(getApplicationContext(), "ID Value = " + uID + " Position = " + position, Toast.LENGTH_LONG).show();

                            DBCommands.deleteExercise(context, uID);
reload();
                        }
                    }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {  //not removing items if cancel is done
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mAdapter.notifyItemRemoved(position + 1);    //notifies the RecyclerView Adapter that data in mAdapter has been removed at a particular position.
                            mAdapter.notifyItemRangeChanged(position, mAdapter.getItemCount());   //notifies the RecyclerView Adapter that positions of element in mAdapter has been changed from position(removed element index to end of list), please update it.
                        }
                    }).show();  //show alert dialog

                }
            }


        };
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }

    public void reload(){
        arrayList = DBCommands.getExercise(context);
         adapter=new exercisesAdapter(this,arrayList);
**recyclerView.setAdapter(adapter);**
adapter.notifyDataSetChanged();

    }
}

答案 1 :(得分:0)

将您的代码更改为以下代码

 public class mainScreen extends AppCompatActivity {
Context context = mainScreen.this;
ImageButton addButtonj;
Intent intent;
exercisesAdapter adapter;
RecyclerView.Adapter mAdapter;
ArrayList<Exercise> arrayList = new ArrayList();

RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    addButtonj = (ImageButton) findViewById(R.id.addButton);


    recyclerView =  (RecyclerView)findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    arrayList = DBCommands.getExercise(context);

     adapter = new exercisesAdapter(mainScreen.this, arrayList);
    recyclerView.setAdapter(adapter);

    addButtonj.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            intent = new Intent(mainScreen.this, addingExercise.class);
            startActivity(intent);
        }
    });


    ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
            final int position = viewHolder.getAdapterPosition(); //get position which is swipe

            if (direction == ItemTouchHelper.LEFT) {    //if swipe left

                AlertDialog.Builder builder = new AlertDialog.Builder(mainScreen.this); //alert for confirm to delete
                builder.setMessage("Are you sure to delete?");    //set message

                builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() { //when click on DELETE
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        TextView theName = (TextView) viewHolder.itemView.findViewById(R.id.textView8);
                        String uID = theName.getText().toString();
                        Toast.makeText(getApplicationContext(), "ID Value = " + uID + " Position = " + position, Toast.LENGTH_LONG).show();

                        DBCommands.deleteExercise(context, uID);
reload();
                    }
                }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {  //not removing items if cancel is done
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mAdapter.notifyItemRemoved(position + 1);    //notifies the RecyclerView Adapter that data in mAdapter has been removed at a particular position.
                        mAdapter.notifyItemRangeChanged(position, mAdapter.getItemCount());   //notifies the RecyclerView Adapter that positions of element in mAdapter has been changed from position(removed element index to end of list), please update it.
                    }
                }).show();  //show alert dialog

            }
        }


    };
    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);
}

public void reload(){
    arrayList = DBCommands.getExercise(context);
     adapter=new exercisesAdapter(this,arrayList);
**recyclerView.setAdapter(adapter);**
adapter.notifyDataSetChanged();

}
 }

您试图在创建问题的onCreate方法中将recyclerview初始化为新对象

答案 2 :(得分:0)

如果不起作用,请按照 Nilesh Rathod 回答。转到xml并检查布局中的recyclerView的ID。

recyclerView = (RecyclerView) findViewById(R.id.recyclerView);