Android 如何访问RecyclerView';s行';s布局文件';s

Android 如何访问RecyclerView';s行';s布局文件';s,android,android-recyclerview,Android,Android Recyclerview,我的RecyclerView行中有一个开关小部件。我想访问该小部件以设置交换机上的setOnCheckedChangeListener,这样当我在mainActivity中的交换机上使用findViewById时,它就可以正常工作了。但是当我执行代码时,应用程序会因为这个错误而崩溃 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.raunak.alarmdemo4/com.raunak.alarmdem

我的RecyclerView行中有一个开关小部件。我想访问该小部件以设置交换机上的setOnCheckedChangeListener,这样当我在mainActivity中的交换机上使用findViewById时,它就可以正常工作了。但是当我执行代码时,应用程序会因为这个错误而崩溃

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.raunak.alarmdemo4/com.raunak.alarmdemo4.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference 
但是为什么会出现NullPointerException???

下面是代码片段 主要活动:

public class MainActivity extends AppCompatActivity implements AlarmRecyclerViewInterface {

    FloatingActionButton mAlarmAddButton;
    RecyclerView mRecyclerView;
    SQLiteDatabase db;
    AlarmsDBhelperClass mAlarmsDBhelperClass;
    ArrayList<String> nameArrayList = new ArrayList<>();
    ArrayList <String> modeArrayList = new ArrayList<>();
    ArrayList<String> repeatArrayList = new ArrayList<>();
    ArrayList<String> hoursArrayList = new ArrayList<>();
    ArrayList<String> minArrayList = new ArrayList<>();
    Switch mSwitch;
    AlarmAdapter.AlarmView mAlarmView;
    AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
    ImageView emptyImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        //Initializing RecyclerView, DatabaseHelperClass, FAB button, The ON OFF switch & the empty ImageView
        mAlarmsDBhelperClass = new AlarmsDBhelperClass(getApplicationContext());
        mAlarmAddButton = findViewById(R.id.btnAlarmADD);
        mRecyclerView = findViewById(R.id.alarmList);
        mSwitch = findViewById(R.id.onoff);
        emptyImageView = findViewById(R.id.empty_view);

        //DividerItemDecoration class is used for getting a vertical line between rows of RecyclerView
        DividerItemDecoration itemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        mRecyclerView.addItemDecoration(itemDecoration);

        //Getting a writable reference of the Database.
        db = mAlarmsDBhelperClass.getWritableDatabase();

        //Retrieving values from the database and storing them in custom ArrayLists
        boolean isDataEmpty = getAlarm(db);

        //Checking if our arrayList is empty? if yes then display some empty list text or an image
        if (!isDataEmpty){
            mRecyclerView.setVisibility(View.GONE);
            emptyImageView.setImageResource(R.drawable.no_alarm_black_white);
            emptyImageView.setVisibility(View.VISIBLE);
        }
        else {
            mRecyclerView.setVisibility(View.VISIBLE);
            emptyImageView.setVisibility(View.GONE);
        }

        //FAB Event handling
        mAlarmAddButton.setImageResource(R.drawable.addalarm);
        mAlarmAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent = new Intent(getApplicationContext(), AddAlarm.class);
                startActivity(mIntent);
            }
        });

        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    Calendar c = Calendar.getInstance();
                    c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hoursArrayList.get(mAlarmView.getAdapterPosition())));
                    c.set(Calendar.MINUTE, Integer.parseInt(minArrayList.get(mAlarmView.getAdapterPosition())));
                    c.set(Calendar.SECOND, 0);
                    startAlarm(c);
                    Toast.makeText(getApplicationContext(),"Alarm Turned ON !",Toast.LENGTH_SHORT).show();
                }else{
                    cancelAlarm();
                    Toast.makeText(getApplicationContext(),"Alarm Turned OFF !",Toast.LENGTH_SHORT).show();
                }
            }
        });

       //Warping up with the recyclerView
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        mRecyclerView.setAdapter(alarmAdapter);
        mRecyclerView.setHasFixedSize(true);
    }

    public boolean getAlarm(SQLiteDatabase db) {
        Cursor cursor = db.rawQuery("SELECT * FROM alarms", new String[]{});
        boolean rowExists;
        if (cursor.moveToFirst()) {
            do {
                nameArrayList.add(cursor.getString(2));
                modeArrayList.add(cursor.getString(3));
                repeatArrayList.add(cursor.getString(4));
                hoursArrayList.add(Integer.toString(cursor.getInt(5)));
                minArrayList.add(Integer.toString(cursor.getInt(6)));
                rowExists = true;
            } while (cursor.moveToNext());
        }else {
            rowExists = false;
        }
        cursor.close();
        return rowExists;
    }

    //RecyclerView's onClick()
    @Override
    public void onItemClick(int position) {
        Toast.makeText(this, "Alarm Clicked !", Toast.LENGTH_SHORT).show();
    }

    //RecyclerView's onLongClick()
    @Override
    public void onLongItemClick(int position) {
        //Updating the recyclerView
        alarmAdapter.notifyItemRemoved(position);
        //Deleting the row from the database
        db.delete("alarms","alarm_name=?",new String[]{nameArrayList.get(position)});
        hoursArrayList.remove(position);
        Toast.makeText(this,"Alarm Deleted !", Toast.LENGTH_SHORT).show();

    }

    public void startAlarm(Calendar c){
        //Getting a System service for the alarm to check the current time with the Alarm set time.
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        //Creating an intent to invoke the onReceive method  in the custom receiver class, just to display notifications.
        Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);

        //A pending intent is used to execute some work in the future with our applications permissions.
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),1,intent,0);

        //Now RTC_WAKEUP means if the device is Switched off turn it on.
        //getTimeInMillis() will get get the time in Milliseconds
        //Schedule an alarm to be delivered precisely at the stated time.In my case it's the calendar's getTimeMillis() method. which is providing the correct time in milliseconds.
        alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
    }

    public void cancelAlarm(){
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(),AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),1,intent,0);

        //Now i'm cancelling the scheduled alarm using AlarmManager's cancel().
        alarmManager.cancel(pendingIntent);
    }
}
public类MainActivity扩展AppCompatActivity实现AlarmRecycleServiceInterface{
浮动操作按钮mAlarmAddButton;
回收视图mRecyclerView;
sqlitedb数据库;
报警SDBHELPERCLASS mAlarmsDBhelperClass;
ArrayList name ArrayList=新的ArrayList();
ArrayList modeArrayList=新建ArrayList();
ArrayList repeatArrayList=新的ArrayList();
ArrayList hoursArrayList=新建ArrayList();
ArrayList minArrayList=新的ArrayList();
开关;
AlarmAdapter.AlarmView-mAlarmView;
AlarmAdapter AlarmAdapter=新的AlarmAdapter(小时ArrayList、minArrayList、modeArrayList、repeatArrayList、nameArrayList、this);
图像视图清空图像视图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Picture);
//初始化RecyclerView、DatabaseHelperClass、FAB按钮、开关和空图像视图
mAlarmsDBhelperClass=新的报警SDBHELPERCLASS(getApplicationContext());
mAlarmAddButton=findViewById(R.id.btnalmadd);
mRecyclerView=findviewbyd(R.id.alarmList);
mSwitch=findviewbyd(R.id.onoff);
emptyImageView=findViewById(R.id.empty\u视图);
//DividerItemDecoration类用于获取RecyclerView行之间的垂直线
DividerItemDecoration=新的DividerItemDecoration(此为DividerItemDecoration.VERTICAL);
mRecyclerView.附加装饰(项目装饰);
//获取数据库的可写引用。
db=malarmsdbhelpersclass.getWritableDatabase();
//从数据库检索值并将其存储在自定义ArrayList中
布尔值isDataEmpty=getAlarm(db);
//检查arrayList是否为空?如果是,则显示一些空列表文本或图像
如果(!isDataEmpty){
mRecyclerView.setVisibility(View.GONE);
emptyImageView.setImageResource(R.drawable.no_alarm_black_white);
emptyImageView.setVisibility(View.VISIBLE);
}
否则{
mRecyclerView.setVisibility(View.VISIBLE);
emptyImageView.setVisibility(View.GONE);
}
//FAB事件处理
mAlarmAddButton.setImageResource(R.drawable.addalarm);
mAlarmAddButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Intent MINENT=新的Intent(getApplicationContext(),AddAlarm.class);
星触觉;
}
});
mSwitch.setOnCheckedChangeListener(新的CompoundButton.OnCheckedChangeListener(){
@凌驾
检查更改后的公共无效(复合按钮复合按钮,布尔b){
如果(b){
Calendar c=Calendar.getInstance();
c、 set(Calendar.HOUR\u OF_DAY,Integer.parseInt(hoursArrayList.get(mAlarmView.getAdapterPosition()));
c、 set(Calendar.MINUTE、Integer.parseInt(minArrayList.get(mAlarmView.getAdapterPosition()));
c、 设置(日历秒,0);
星形臂(c);
Toast.makeText(getApplicationContext(),“报警已打开!”,Toast.LENGTH\u SHORT.show();
}否则{
取消报警();
Toast.makeText(getApplicationContext(),“报警已关闭!”,Toast.LENGTH\u SHORT.show();
}
}
});
//与recyclerView一起扭曲
setLayoutManager(新的LinearLayoutManager(getApplicationContext());
mRecyclerView.setAdapter(alarmAdapter);
mRecyclerView.setHasFixedSize(true);
}
公共布尔getAlarm(SQLiteDatabase db){
Cursor Cursor=db.rawQuery(“从报警中选择*”,新字符串[]{});
布尔行存在;
if(cursor.moveToFirst()){
做{
nameArrayList.add(cursor.getString(2));
modeArrayList.add(cursor.getString(3));
repeatArrayList.add(cursor.getString(4));
添加(Integer.toString(cursor.getInt(5));
add(Integer.toString(cursor.getInt(6));
rowExists=true;
}while(cursor.moveToNext());
}否则{
rowExists=false;
}
cursor.close();
返回行存在;
}
//RecyclerView的onClick()
@凌驾
公共空间单击(内部位置){
Toast.makeText(这是“点击报警!”,Toast.LENGTH_SHORT.show();
}
//RecyclerView的onLongClick()
@凌驾
public void onLongItemClick(内部位置){
//更新recyclerView
alarmAdapter.NotifyItem已移除(位置);
//正在从数据库中删除该行
delete(“alarms”,“alarm_name=?”,新字符串[]{nameArrayList.get(position)});
hoursArrayList.移除(位置);
Toast.makeText(这是“已删除报警!”,Toast.LENGTH_SHORT.show();
}
公共空间startAlarm(日历c){
//获取警报的系统服务,以检查当前时间与警报设置时间。
AlarmManager AlarmManager=(AlarmManager)getSystemService(Context.ALARM\u服务);
//创建一个意图来调用自定义receiver类中的onReceive方法,只是为了显示通知。
意向意向=新意向(getApplicationContext(),AlarmReceiv)
<Switch
    android:id="@+id/onoff"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="15dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.412" />
public class AlarmAdapter extends RecyclerView.Adapter<AlarmAdapter.AlarmView> {
    //Variables for the main recycler view
    private ArrayList<String> hoursArrayList;
    private ArrayList<String> minArrayList;
    private ArrayList<String> modeArrayList;
    private ArrayList<String> repeatArrayList;
    private ArrayList<String> nameArrayList;
    private AlarmRecyclerViewInterface mInterface;

    public AlarmAdapter(ArrayList<String> hours,ArrayList<String> mins,ArrayList<String> mode,ArrayList<String> repeat,ArrayList<String> name,AlarmRecyclerViewInterface mInterface){
        this.hoursArrayList = hours;
        this.minArrayList = mins;
        this.modeArrayList = mode;
        this.nameArrayList = name;
        this.repeatArrayList = repeat;
        this.mInterface = mInterface;
    }

    @NonNull
    @Override
    public AlarmView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.alarm_profile,parent,false);
        return new AlarmView(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AlarmView holder, int position) {
        if(Integer.parseInt(hoursArrayList.get(position)) < 10 ){
            holder.hours.setText("0"+hoursArrayList.get(position));
        }else {
            holder.hours.setText(hoursArrayList.get(position));
        }
        if (Integer.parseInt(minArrayList.get(position)) < 10){
            holder.mins.setText("0"+minArrayList.get(position));
        }else {
            holder.mins.setText(minArrayList.get(position));
        }
        holder.repeat.setText(repeatArrayList.get(position));
        holder.mode.setText(modeArrayList.get(position));
        holder.name.setText(nameArrayList.get(position));
    }

    @Override
    public int getItemCount() {
        return hoursArrayList.size();
    }

    /*ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            nameArrayList.remove(viewHolder.getAdapterPosition());
            modeArrayList.remove(viewHolder.getAdapterPosition());
            repeatArrayList.remove(viewHolder.getAdapterPosition());
            hoursArrayList.remove(viewHolder.getAdapterPosition());
            minArrayList.remove(viewHolder.getAdapterPosition());
        }
    };*/

    public class AlarmView extends RecyclerView.ViewHolder{
        TextView hours,mins,repeat,name,mode;
        public AlarmView(@NonNull View itemView) {
            super(itemView);
            hours = itemView.findViewById(R.id.txtHOUR);
            mins = itemView.findViewById(R.id.txtMins);
            repeat = itemView.findViewById(R.id.txtRepeatDays);
            name = itemView.findViewById(R.id.txtName);
            mode = itemView.findViewById(R.id.txtMode);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mInterface.onItemClick(getAdapterPosition());
                }
            });

            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mInterface.onLongItemClick(getAdapterPosition());
                    return true;
                }
            });

        }
    }

}
void startCancelAlarm(boolean isStart, int position);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    mInterface.startCancelAlarm(b,getAdapterPosition());
                }
            });

                                                 ^
@Override
    public void startCancelAlarm(boolean isStart, int position) {
        if(isStart){
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hoursArrayList.get(position)));
            c.set(Calendar.MINUTE, Integer.parseInt(minArrayList.get(position)));
            c.set(Calendar.SECOND, 0);
            startAlarm(c);
            Toast.makeText(getApplicationContext(),"Alarm Turned ON !",Toast.LENGTH_SHORT).show();
        }else{
            cancelAlarm();
            Toast.makeText(getApplicationContext(),"Alarm Turned OFF !",Toast.LENGTH_SHORT).show();
        }
    }