Home > OS >  How to show recylcer view items on app start when data comes from datastore?
How to show recylcer view items on app start when data comes from datastore?

Time:06-08

I am using recylcer view on a fragment and fetching the data that to show on recycler view form datastore through query.I want to show the data on recycler view on opeing the app like youtube and instagram but I can't do that. When I add a button and put the recyler.setadapter in onClicklister it worked after the button clicked.But I want to do that on app start.If you are confused then look at the below code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view=inflater.inflate(R.layout.fragment_home, container, false);
    recyclerView=view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    arrayList=new ArrayList<>();
  apiQuery();
    adapter=new MyAdapter(getContext(),arrayList);
    view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            recyclerView.setAdapter(adapter);
        }
    });

    return view;
}
private void apiQuery(){
    Amplify.API.query(
            ModelQuery.list(Todo.class, Todo.NAME.contains(" ")),
            response -> {
                for (Todo todo : response.getData()) {
                  arrayList.add(todo);
                    Log.i("MyAmplifyApp", todo.getName());
                }
            },
            error -> Log.e("MyAmplifyApp", "Query failure", error)
    );
}

CodePudding user response:

You are setting the adapter in the button click method. You can preload the data on splash screen etc and save the data on device and then when your fragment/activity is loaded. You can set the adapter to load the data.

CodePudding user response:

You have to send data to Adapter class after receiving response from API. Then update your recyclerview adapter's list and call notifyDataSetChanged() method.

Refer below sample code;

In Fragment

response -> {
                for (Todo todo : response.getData()) {
                  arrayList.add(todo);
                    Log.i("MyAmplifyApp", todo.getName());
                }
                adapter.updateData(arrayList)
            }

In Adapter class

fun updateData(list: ArrayList<Model>) {
    arraylist.addAll(list)
    notifyDataSetChanged()
}
  • Related