S
S
SimpleName2019-10-20 19:56:40
Java
SimpleName, 2019-10-20 19:56:40

How to implement recreating ArrayList for ReyclerView depth navigation?

I'm trying to build navigation based on ArrayList. The logic is quite simple - if parent_id is equal to 0, then these elements are highlighted immediately when switching to a fragment with a RecyclerView. This request from Dao is responsible for this.

@Query("SELECT * from word_table WHERE parent_id = 0")
LiveData<List<Word>> getAlphabetizedWords();

After clicking on an element from the initial list, the ArrayList should be completely cleared and filled with those elements whose parent_id , for example, is 1
@Query("SELECT * FROM word_table WHERE parent_id = :id")
LiveData<List<Word>> getAlphabetizedWords(final int id);

This should continue until all items in the newly created list have had_products = true. Since there is no true in sql, you need to get 1. To do this, you can try this dao query (probably)
@Query("SELECT has_products FROM WORD_TABLE WHERE has_products = 1")
boolean hasProduct();

Any ideas on how to write the code for all of this?.
Here is an example database
5dac90f8d707a769713350.jpeg
Here are the codes
WordRoomDatabase

@Database(entities = {Word.class}, version = 6, exportSchema = false)
public abstract class WordRoomDatabase extends RoomDatabase {

    public abstract WordDao wordDao();

    // marking the instance as volatile to ensure atomic access to the variable
    private static volatile WordRoomDatabase INSTANCE;

    static WordRoomDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (WordRoomDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WordRoomDatabase.class, "word_database")
                            .fallbackToDestructiveMigration()
                            .addCallback(sRoomDatabaseCallback)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * Override the onOpen method to populate the database.
     * For this sample, we clear the database every time it is created or opened.
     *
     * If you want to populate the database only when the database is created for the 1st time,
     * override RoomDatabase.Callback()#onCreate
     */
    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            // If you want to keep the data through app restarts,
            // comment out the following line.
            new PopulateDbAsync(INSTANCE).execute();
        }
    };

    /**
     * Populate the database in the background.
     * If you want to start with more words, just add them.
     */
    private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {

        private final WordDao mDao;

        PopulateDbAsync(WordRoomDatabase db) {
            mDao = db.wordDao();
        }

        @Override
        protected Void doInBackground(final Void... params) {
            // Start the app with a clean database every time.
            // Not needed if you only populate on creation.
            mDao.deleteAll();

            Word word = new Word(
                    1,
                    0,
                    "Category 1",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",false);
            mDao.insert(word);
            word = new Word(
                    2,
                    0,
                    "Category 2",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",false);
            mDao.insert(word);
            word = new Word(
                    3,
                    0,
                    "Category 3",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",false);
            mDao.insert(word);
            word = new Word(
                    4,
                    0,
                    "Category 4",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",false);
            mDao.insert(word);
            word = new Word(
                    5,
                    1,
                    "Subcategory 1.1",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",true);
            mDao.insert(word);
            word = new Word(
                    6,
                    1,
                    "Subcategory 1.2",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",true);
            mDao.insert(word);
            word = new Word(
                    7,
                    1,
                    "Subcategory 1.3",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",true);
            mDao.insert(word);
            word = new Word(
                    8,
                    2,
                    "Subcategory 2.1",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",true);
            mDao.insert(word);
            word = new Word(
                    9,
                    2,
                    "Subcategory 2.2",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",true);
            mDao.insert(word);
            word = new Word(
                    10,
                    3,
                    "Subcategory 3.1",
                    "http://185.83.242.116/media/photo_2018-08-20_12-55-11.jpg",true);
            mDao.insert(word);
            return null;
        }
    }
}


MainActivity

public class MainActivity extends AppCompatActivity {

    public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
    private int parentId;
    private ArrayList<MenuPosition> ourMenuItems;
    private ArrayList<Word> list;

    private WordViewModel mWordViewModel;

    public MainActivity() {
        this.ourMenuItems = new ArrayList<>();
    }

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

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        final WordListAdapter adapter = new WordListAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter.setOnItemClickListener(new WordListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Word word) {
                //Toast toast = Toast.makeText(getApplicationContext(), "Products",Toast.LENGTH_SHORT);
                //toast.show();
                UpdateData();
            }
        });


        // Get a new or existing ViewModel from the ViewModelProvider.
        mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class);

        mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
            @Override
            public void onChanged(@Nullable final List<Word> words) {
                // Update the cached copy of the words in the adapter.
                adapter.setWords(words);
            }
        });
    }

}


WorldListAdapter

public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {


    class WordViewHolder extends RecyclerView.ViewHolder{
        private final TextView wordItemView;
        private final ImageView imageView;

        private WordViewHolder(View itemView) {
            super(itemView);
            wordItemView = itemView.findViewById(R.id.textView);
            imageView = itemView.findViewById(R.id.imageView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if (listener != null && position != RecyclerView.NO_POSITION){
                        listener.onItemClick(mWords.get(position));
                    }
                }
            });
        }
    }

    private final LayoutInflater mInflater;
    private List<Word> mWords; // Cached copy of words
    private OnItemClickListener listener;

    WordListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public WordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new WordViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(WordViewHolder holder, int position) {
        if (mWords != null) {
            Word current = mWords.get(position);
            holder.wordItemView.setText(current.getWord());
            Picasso.get().load(current.getImage()).into(holder.imageView);
        } else {
            // Covers the case of data not being ready yet.
            holder.wordItemView.setText("No Word");
        }
    }

    void setWords(List<Word> words) {
        mWords = words;
        notifyDataSetChanged();
    }

    // getItemCount() is called many times, and when it is first called,
    // mWords has not been updated (means initially, it's null, and we can't return null).
    @Override
    public int getItemCount() {
        if (mWords != null)
            return mWords.size();
        else return 0;
    }

    public interface OnItemClickListener {
        void onItemClick(Word word);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener=listener;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2019-11-02
@onepavel

I wouldn't touch arrayList myself.
I see three options:
1. network a new list with data in the recycler and call a data refresh
2. send a new adapter with a data list to the recycler and refresh
3. do it on fragments, as file managers do for navigating through folders

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question