无法从RecyclerView适配器类调用方法

时间:2018-04-30 11:57:46

标签: java android android-recyclerview

我创建了一个recyclerView -

public class PlayerListRecyclerViewAdapter extends RecyclerView.Adapter<PlayerListRecyclerViewAdapter.ViewHolder>


 playerAdapter = new PlayerListRecyclerViewAdapter(this,cursor, playerDataSet);
        playerRecyclerView.setAdapter(playerAdapter);

一切正常,但我创建了以下方法:

public void swapCursor(Cursor newCursor) {
    // Always close the previous mCursor first
    if (pCursor != null) pCursor.close();
    pCursor = newCursor;
    if (newCursor != null) {
        // Force the RecyclerView to refresh
        this.notifyDataSetChanged();
    }
}

但是当我尝试从链接到适配器的活动中调用它时,它找不到它:

 new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //Do nothing, we are not moving anything
                //But maybe we can let the user arrange their list?
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                long id = (long) viewHolder.itemView.getTag();
                removePlayer(id);
                playerAdapter.swapCursor(getAllPlayers());

            }
        }).attachToRecyclerView(playerRecyclerView);
    }

交换cusor为红色,在适配器中显示从未使用的消息。

我想跟随:

https://github.com/udacity/ud851-Exercises/blob/student/Lesson07-Waitlist/T07.05-Solution-AddGuests/app/src/main/java/com/example/android/waitlist/GuestListAdapter.java

但我不确定我错过了什么? 其他一切正常,我可以刷卡,它加载细节。所有好的只是出于某种原因调用这种方法是行不通的。

2 个答案:

答案 0 :(得分:0)

请检查您的播放器适配器是否为空值。

因为在定义playeradapter对象后访问了swapCursor方法。

if(playerAdapter!=null){
playerAdapter.swapCursor(getAllPlayers());     
}

答案 1 :(得分:0)

检查您的代码是否有playerAdapter的声明。 它应该是: -

PlayerListRecyclerViewAdapter playerAdapter;

<强>与其使用

RecyclerView.Adapter playerAdapter;