有没有办法检查Adapter类之外的RecyclerView类是否为空?

如何解决有没有办法检查Adapter类之外的RecyclerView类是否为空?

我正在构建这个简单的记事本应用程序。所有笔记都托管在RecyclerView中,并且有一个按钮可用于删除所有笔记。现在,当用户按下按钮删除所有笔记时,将弹出一个AlertDialog。事实是,即使应用程序中没有注释,也会弹出此AlertDialog。我想阻止那个。仅在有注释存在时才弹出AlertDialog。

我想知道是否可以通过某种方法从Adapter类中获取Activity中的RecyclerView大小。我认为这将是实现这一目标的最佳方法。如果有更好的方法,一定要让我知道。

以下是各个类别:

NotesActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.ActivityNotesBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.Constants;
import com.arpansircar.java.notepadapplicationusingmvvm.model.INotesActivity;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesDatabase;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import com.arpansircar.java.notepadapplicationusingmvvm.viewmodel.NotesActivityViewModel;

import java.util.List;
import java.util.Objects;

/**
 * The NotesActivity is the primary activity in the entire applications.
 * This activity starts up and shows the user all the notes that have been created or the facility to add a new note using the floating action button.
 * All the notes that have been created using this application and short details associated with them show up in the RecyclerView.
 * The user can click on any of these notes to view the complete details of the note.
 */
public class NotesActivity extends AppCompatActivity implements View.OnClickListener,INotesActivity {

    private ActivityNotesBinding activityNotesBinding;
    private NotesActivityViewModel notesActivityViewModel;

    /*The onCreate method is the first method that is executed when the application starts up.
     * Usually,in this method,such functions are executed that are to be performed only once.
     * In this method,I've defined two other methods to be executed as soon as the application starts up and that are to be executed only once.
     * The initializeDatabase() method is used to create an instance of the RoomDatabase.
     * An application context is used because we want to use the same instance throughout the context of the application.
     * The initializeViewModel() is used to create an instance of the ViewModel class associated with this activity.
     * This ViewModel will be used to handle any configuration changes. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityNotesBinding = DataBindingUtil.setContentView(this,R.layout.activity_notes);
        initializeDatabase();
        initializeViewModel();
    }

    /*The onStart() is the next method executed after the onCreate() callback method.
     * In this method,two methods are executed,namely the setOnClickListenerMethod() and the setObserverMethod().
     * The setOnClickListenerMethod() method is tasked with setting the onClickListener for any and all buttons that might exist in the activity.
     * Currently,the activity has a single floating action button so this button's onClickListener is set in this activity.
     * The setObservableMethod() method is used to activate the Observer to observe changes in the LiveData object present in the ViewModel. */
    @Override
    protected void onStart() {
        super.onStart();
        setOnClickListenerMethod();
        setObserverMethod();
    }

    /*The initializeDatabase() method is used to create an instance of the NotesDatabase class.
     * This single instance will be used for performing all the database transactions including the CRUD operations.
     * For creating an instance of this class,the application context is used.
     * I've assumed that using an application context will allow me to use the instance throughout the entirety of the application.*/
    private void initializeDatabase() {
        NotesDatabase.initializeDatabase(getApplicationContext());
    }

    /*The initializeViewModel() method is used for initializing the NotesActivityViewModel instance with the ViewModel class.*/
    private void initializeViewModel() {
        notesActivityViewModel = new ViewModelProvider(this).get(NotesActivityViewModel.class);
    }

    /*The setObserverMethod() method is used simply for activating the observer.
     * This task is done at the Started state of the activity to allow it to start observing the changes in the LiveData as soon as the activity starts.
     * If there are any changes in the database,i.e.,if it returns a List of NotesEntity objects,the list is sent to the setRecyclerViewMethod().*/
    private void setObserverMethod() {
        final Observer<List<NotesEntity>> observer = this::setRecyclerViewMethod;
        notesActivityViewModel.selectAllNotesMethod().observe(this,observer);
    }

    /*The setRecyclerViewMethod(...) is called when the observer observes a change in the LiveData.
     * Upon calling this method,the List of NotesEntity objects are passed into this method which promptly passes it to the RecyclerViewAdapter class.
     * Accordingly,the RecyclerView is populated with the required views and a new RecyclerView is displayed with the newly added notes.*/
    private void setRecyclerViewMethod(List<NotesEntity> notesEntityList) {
        RecyclerView recyclerView = activityNotesBinding.notesListRecyclerView;
        NotesAdapter notesAdapter = new NotesAdapter(notesEntityList,this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(false);
        recyclerView.setAdapter(notesAdapter);
    }

    /*The setOnClickListenerMethod() is used to set the onClickListener to all the floating action buttons used in the activity.*/
    private void setOnClickListenerMethod() {
        activityNotesBinding.newNoteFloatingActionButton.setOnClickListener(this);
        activityNotesBinding.deleteAllNotesFloatingActionButton.setOnClickListener(this);
    }

    /*The onClick(...) method allows us to intercept all the clicks placed within this method.
     * Since,only a single view can be clicked in this activity,therefore,this method contains only a single if clause.
     * The if clause checks if the floating action button has been clicked or not.
     * If it has,an Intent object starts the AddEditActivity for the user to add a new note to the activity. */
    @Override
    public void onClick(View view) {
        if (view == activityNotesBinding.newNoteFloatingActionButton) {
            Intent newNoteIntent = new Intent(NotesActivity.this,AddEditNoteActivity.class);
            newNoteIntent.putExtra("function","insert");
            startActivity(newNoteIntent);
        }

        if (view == activityNotesBinding.deleteAllNotesFloatingActionButton) {
            AlertDialog alertDialog = showAlertDialogMethod(
                    "delete_all",getString(R.string.delete_all_notes_alert_title),getString(R.string.delete_all_notes_alert_message));
            alertDialog.show();
        }
    }

    /*The onNoteClicked(...) method here is an overridden method from the INotesActivity interface.
     * When a note is clicked in the RecyclerView,the clicked noteID is transferred to this method.
     * When this method is triggered,an Intent object is created to start the DisplayNoteActivity.java activity.
     * Within this object,the noteID of the clicked note is sent as an Integer extra to next activity.
     * Finally,the activity is started.*/
    @Override
    public void onNoteClicked(NotesEntity notesEntity) {
        Intent intent = new Intent(NotesActivity.this,DisplayNoteActivity.class);
        intent.putExtra(Constants.COLUMN_ID,notesEntity.getId());
        startActivity(intent);
    }

    private AlertDialog showAlertDialogMethod(String function,String title,String message) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(R.string.yes_string,(dialogInterface,i) -> {
                    if (Objects.equals(function,"exit"))
                        super.onBackPressed();

                    if (Objects.equals(function,"delete_all"))
                        notesActivityViewModel.deleteAllNotesMethod();
                })

                .setNegativeButton(R.string.no_string,i) -> dialogInterface.cancel());

        return alertDialogBuilder.create();
    }

    @Override
    public void onBackPressed() {
        AlertDialog alertDialog = showAlertDialogMethod(
                "exit",getString(R.string.exit_title),getString(R.string.exit_message));

        alertDialog.show();
    }
}

NotesAdapter.java

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.IndividualItemsLayoutBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.INotesActivity;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;

import java.util.List;

/**
 * The NotesAdapter class is used for setting up the RecyclerView.
 * The class accepts a List of NotesEntity objects as the argument for it's constructor.
 * This list is used to populate the RecyclerView with newer objects.
 */
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NotesViewHolder> {

    private final List<NotesEntity> notesEntityList;
    private final INotesActivity iNotesActivity;

    public NotesAdapter(List<NotesEntity> notesEntityList,INotesActivity iNotesActivity) {
        this.notesEntityList = notesEntityList;
        this.iNotesActivity = iNotesActivity;
    }

    /*The onCreateViewHolder() method configures and returns the views for all the different objects present in the List.*/
    @NonNull
    @Override
    public NotesViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
        IndividualItemsLayoutBinding individualItemsLayoutBinding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()),R.layout.individual_items_layout,parent,false
        );

        return new NotesViewHolder(individualItemsLayoutBinding,iNotesActivity);
    }

    /*The onBindViewHolder(...) method receives the views individually from the NotesViewHolder class.
     * This method then binds all these individual views to the list.*/
    @Override
    public void onBindViewHolder(@NonNull NotesViewHolder holder,int position) {
        NotesEntity currentNote = notesEntityList.get(position);
        holder.individualItemsLayoutBinding.setNoteDetails(currentNote);
    }

    /*The getItemCount() method simply returns the value denoting the size that our RecyclerView is supposed to be. */
    @Override
    public int getItemCount() {
        if (notesEntityList != null) {
            return notesEntityList.size();
        } else {
            return 0;
        }
    }

    /*The NotesViewHolder class is used to hold each of the views for each of the objects present in the notesEntitiesList list.*/
    public class NotesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private final IndividualItemsLayoutBinding individualItemsLayoutBinding;
        private final INotesActivity iNotesActivity;

        public NotesViewHolder(@NonNull IndividualItemsLayoutBinding individualItemsLayoutBinding,INotesActivity iNotesActivity) {
            super(individualItemsLayoutBinding.getRoot());
            this.individualItemsLayoutBinding = individualItemsLayoutBinding;
            individualItemsLayoutBinding.getRoot().setOnClickListener(this);
            this.iNotesActivity = iNotesActivity;
        }

        /*The onClick(...) method is used when we click a particular view present in the RecyclerView.
         * When the user clicks on a particular note,this method stores the object for that particular note from the list.
         * Next,the noteID is acquired from the object and is sent to the NotesActivity via the INotesActivity interface.*/
        @Override
        public void onClick(View view) {
            iNotesActivity.onNoteClicked(notesEntityList.get(getAdapterPosition()));
        }
    }
}

感谢您的帮助。

解决方法

这可能有帮助:

 if(layoutManager.findViewByPosition(0)==null){
 that means recycler view is empty
}

请先进行测试,以确保在非空回收器视图上进行尝试,并确保当第0个位置行不在场景中时不提供null。如果给出非null值,我们很好。同样,如果可行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-