Problem with Recycler view in android studio – Only appearing occasionally

The problem here is you are adding object to accounts but not notifying the Adapter about the change . Make the following changes to your code . For setting adapter inside onCreate() use Only .

private RecyclerViewAdapterAccounts adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manage_accounts);
    initAccounts();
    RecyclerView recyclerView = findViewById(R.id.recycler_view_accounts);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new RecyclerViewAdapterAccounts(accounts, this);
    recyclerView.setAdapter(adapter);
}

Now create a method in RecyclerViewAdapterAccounts to add elements in adapter ;

public void addAll(ArratList<String> list){
        mlist.clear();// To clear list if thats the case
        mlist.addAll(list);
        notifyDataSetChanged();
    }

Now you can add all elements in one go to adapter .

public void onDataChange(@NonNull DataSnapshot snapshot) {
        ArrayList<String> dataList=new ArrayList<>();
        Iterator<DataSnapshot> children = snapshot.getChildren().iterator();
        while (children.hasNext()) {
            DataSnapshot child = children.next();
            String[] parts = child.getValue().toString().split(",");
            String role = parts[0].replace('{', ' ');
            String msg = child.getKey() + ": " + role;
            dataList.add(msg);
        }
        adapter.addAll(dataList);
    }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top