For loop not working on my Query Firestore - java

I'm stuck in a project which I need to get the data from document in a collection. I'm currently using Firestore for Android Studio. The fact is that my query shows the toast just after the task.isSuccessful but the For loop is not getting the data from the Cloud, not even showing the test Toast I put inside the loop. Everything works fine till get to the For loop. The RecyclerView only shows content if I put parameters manually
for test so Adapter is working fine but when I try to show the data from the firestorm it shows nothing! Any idea? It does not show any error!
public class MostrarConteudoFragment extends AppCompatActivity {
RecyclerView recyclerView2;
List<Compras> listaCompras = new ArrayList<>();
Compras compras;
FirebaseFirestore db;
FirebaseUser user;
FirebaseAuth mAuth;
SavedFragment savedFragment;
public String idUpdate = ""; // id do item para o update
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mostrar_conteudo_fragment);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance( );
user = mAuth.getCurrentUser( );
recyclerView2 = findViewById(R.id.recyclerView2);
savedFragment = new SavedFragment();
}
protected void onStart(){
super.onStart();
if(listaCompras.size() > 0)
listaCompras.clear();
db.collection("Usuario").document(user.getUid()).collection("ItensSalvos")
.whereEqualTo("id", idUpdate).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(MostrarConteudoFragment.this, "task succcessful", Toast.LENGTH_SHORT).show( );
for (QueryDocumentSnapshot doc : task.getResult( )) {
Toast.makeText(MostrarConteudoFragment.this, "doc succcessful", Toast.LENGTH_SHORT).show( );
compras = new Compras(doc.getString("id"),
doc.getString("inputNome"),
doc.getString("inputQtd"),
doc.getString("inputPreco"),
doc.getBoolean("checkBoxOk"));
listaCompras.add(compras);
}
//Configurar adapter
AdapterMostrarConteudo mostrarConteudo = new AdapterMostrarConteudo(MostrarConteudoFragment.this, listaCompras);
//Configurar RecyclerView
RecyclerView.LayoutManager layoutManager1 = new LinearLayoutManager(getApplicationContext( ));
recyclerView2.setLayoutManager(layoutManager1);
recyclerView2.setHasFixedSize(true);
recyclerView2.setAdapter(mostrarConteudo);
}
}
});
}
}
public class AdapterSave extends RecyclerView.Adapter {
List<DataHora> listaDataHora;
SavedFragment savedFragment;
MostrarConteudoFragment mostrarConteudo;
public AdapterSave(SavedFragment savedFragment, List<DataHora> listaDataHora) {
this.savedFragment = savedFragment;
this.listaDataHora = listaDataHora;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemLista = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.lista_salvas, viewGroup, false);
mostrarConteudo = new MostrarConteudoFragment();
return new MyViewHolder(itemLista);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.data.setText(listaDataHora.get(i).getData());
myViewHolder.hora.setText(listaDataHora.get(i).getHora());
myViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
mostrarConteudo.idUpdate = listaDataHora.get(position).getId();
Intent intent = new Intent(savedFragment.getActivity(), MostrarConteudoFragment.class);
savedFragment.startActivity(intent );
Toast.makeText(savedFragment.getContext(), mostrarConteudo.idUpdate, Toast.LENGTH_SHORT).show( );
}
});
}
#Override
public int getItemCount() {
return listaDataHora.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener {
TextView data, hora;
ItemClickListener itemClickListener;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
data = itemView.findViewById(R.id.textData);
hora = itemView.findViewById(R.id.textHora);
}
// Metodo construtor da interface ItemClickListener
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override // Permite abrir o menu com o click
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
}
#Override // Cria o menu quando item é clicado
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
}
}
}
enter image description here
enter image description here

Related

Recyclerview doesn't show any data after swiping one of the rows

I've added swipe to my app, to delete specified note. For couple of days, I've facing problem with displaying data after swipe. For clarify:
Let's say, we have two items in recycler view. Whenever we swipe one of them, the second one should be visible, but it's not until I'll re-run the app. How I may solve it?
Main Activity
public class MainActivity extends AppCompatActivity implements MemoAdapter.OnNoteListener {
private static final String TAG = "MainActivity";
//Vars
private ArrayList<Note> mNotes = new ArrayList<>();
private MemoRepository mRepository;
private MemoAdapter mMemoAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRepository = new MemoRepository(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.memoToolbar);
setSupportActionBar(toolbar);
setTitle("My memos");
initRecyclerView();
}
//This method would be called after getting result from memo_content such as new memo, or edited existing memo.
#Override
protected void onResume() {
super.onResume();
getMemos();
}
private void getMemos(){
mRepository.getAllMemos().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
if (mNotes.size() > 0){
notes.clear();
}
if (notes != null){
mNotes.addAll(notes);
mMemoAdapter.watchMemoChanges((ArrayList<Note>) notes);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.icon_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.addNewNote:
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, memo_content.class));
break;
case R.id.deleteAllNotes:
Toast.makeText(this, "Delete!", Toast.LENGTH_SHORT).show();
mRepository.deleteAllMemos();
break;
}
return super.onOptionsItemSelected(item);
}
private void initRecyclerView(){
//UI
RecyclerView mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mMemoAdapter = new MemoAdapter(mNotes, this);
new ItemTouchHelper(itemTouch).attachToRecyclerView(mRecyclerView);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mMemoAdapter);
}
#Override
public void onMemoClick(int position) {
Intent intent = new Intent(this, memo_content.class);
intent.putExtra("memo_content", mNotes.get(position));
startActivity(intent);
}
private ItemTouchHelper.SimpleCallback itemTouch = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.START | ItemTouchHelper.LEFT) {
#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) {
mRepository.deleteMemo(mNotes.get(viewHolder.getAdapterPosition()));
Log.d(TAG, "onSwiped: "+mNotes.get(viewHolder.getAdapterPosition()));
}
};
}
Adapter
public class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.MemoViewHolder> {
private ArrayList<Note> mNotes;
private OnNoteListener mListener;
public class MemoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, timestamp;
private MemoViewHolder(#NonNull final View itemView) {
super(itemView);
this.title = (TextView) itemView.findViewById(R.id.title);
this.timestamp = (TextView) itemView.findViewById(R.id.timestamp);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mListener.onMemoClick(getAdapterPosition());
}
}
public MemoAdapter(ArrayList<Note> notes, OnNoteListener listener) {
this.mNotes = notes;
this.mListener = listener;
}
#NonNull
#Override
public MemoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_memo, parent, false);
return new MemoViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MemoViewHolder holder, int position) {
holder.title.setText(mNotes.get(position).getTitle());
holder.timestamp.setText(mNotes.get(position).getTimestamp());
}
public void watchMemoChanges(ArrayList<Note> notes){
this.mNotes = notes;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mNotes.size();
}
public interface OnNoteListener{
void onMemoClick(int position);
}
Short answer:
You need to remove the statement notes.clear() when you receive a change in the LiveData list from the database via the observer.
Detailed answer
When you first run your app, it will show all right list because the condition if (mNotes.size() > 0) is not met, and so the received list won't be cleared via notes.clear(), so the RecyclerView will display the right data.
But when you delete a note, then when the observer is triggered again with the new list, the condition if (mNotes.size() > 0) will be met, so you will clear the list that is coming from the database before feeding the adapter with it, so the RecyclerView will be free of data.
So to solve this please replace notes.clear(); with mNotes.clear();
So the right code will be:
private void getMemos(){
mRepository.getAllMemos().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
if (mNotes.size() > 0){
mNotes.clear();
}
if (notes != null){
mNotes.addAll(notes);
mMemoAdapter.watchMemoChanges((ArrayList<Note>) notes);
}
}
});
}
Wish that help you out.
I didn't examine the rest of code, please let me know if there is another issue to help more

Android Studio RecyclerView: No adapter attached; skipping layout

Help
the problem is that when running the application nothing appears in my recyclerview, only error android studio : E/RecyclerView: No adapter attached; skipping layout
Salon ListActivity
public class SalonListActivity extends AppCompatActivity implements IOnLoadCountSalon, IBranchLoadListener {
IOnLoadCountSalon iOnLoadCountSalon;
IBranchLoadListener iBranchLoadListener;
AlertDialog dialog;
#BindView(R.id.txt_salon_count)
TextView txt_salon_count;
#BindView(R.id.recycler_salon)
RecyclerView recycler_salon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salon_list);
ButterKnife.bind(this);
initView();
init();
loadSalonBaseOnCity(Common.state_name);
}
private void loadSalonBaseOnCity(String name) {
dialog.show();
FirebaseFirestore.getInstance().collection("AllSalon")
.document(name)
.collection("Branch")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
List<Salon> salons = new ArrayList<>();
iOnLoadCountSalon.onLoadCountSalonSuccess(task.getResult().size());
for(DocumentSnapshot salonSnapShot : task.getResult())
{
Salon salon = salonSnapShot.toObject(Salon.class);
salons.add(salon);
}
iBranchLoadListener.onBranchLoadSuccess(salons);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
iBranchLoadListener.onBranchLoadFailed(e.getMessage());
}
});
}
private void init() {
dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).build();
iOnLoadCountSalon=this;
iBranchLoadListener = this;
}
private void initView() {
recycler_salon.setHasFixedSize(true);
recycler_salon.setLayoutManager(new GridLayoutManager(this,2));
recycler_salon.addItemDecoration(new SpacesItemDecoration(8));
}
#Override
public void onLoadCountSalonSuccess(int count) {
txt_salon_count.setText(new StringBuilder("Cantidad Salones (").append(count).append(")"));
}
#Override
public void onBranchLoadSuccess(List<Salon> salonList) {
MySalonAdapter salonAdapter = new MySalonAdapter(this,salonList);
recycler_salon.setAdapter(salonAdapter);
dialog.dismiss();
}
#Override
public void onBranchLoadFailed(String message) {
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}}`
Salon Adapter
public class MySalonAdapter extends RecyclerView.Adapter<MySalonAdapter.MyViewHolder> {
Context context;
List<Salon> salonList;
List<CardView> cardViewList;
LocalBroadcastManager localBroadcastManager;
public MySalonAdapter(Context context, List<Salon> salonList) {
this.context = context;
this.salonList = salonList;
cardViewList = new ArrayList<>();
localBroadcastManager = LocalBroadcastManager.getInstance(context);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.layout_salon, viewGroup, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.txt_salon_name.setText(salonList.get(i).getName());
myViewHolder.txt_salon_address.setText(salonList.get(i).getAddress());
if (!cardViewList.contains(myViewHolder.card_salon))
cardViewList.add(myViewHolder.card_salon);
myViewHolder.setiRecyckerItemSelectedListener(new IRecyclerItemSelectedListener() {
#Override
public void onItemSelected(View view, int position) {
}
});
}
#Override
public int getItemCount() {
return salonList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
IRecyclerItemSelectedListener iRecyckerItemSelectedListener;
TextView txt_salon_name, txt_salon_address;
CardView card_salon;
public void setiRecyckerItemSelectedListener(IRecyclerItemSelectedListener iRecyckerItemSelectedListener) {
this.iRecyckerItemSelectedListener = iRecyckerItemSelectedListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
card_salon = (CardView) itemView.findViewById(R.id.card_salon);
txt_salon_name = (TextView) itemView.findViewById(R.id.txt_salon_name);
txt_salon_address = (TextView) itemView.findViewById(R.id.txt_salon_address);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
iRecyckerItemSelectedListener.onItemSelected(v, getAdapterPosition());
}
}
}
Sorry for my English I hope you can help me, I will be very grateful
The message is saying that the adapter is not attached at the time the layout is rendered. Which is true because you've attached it within a callback method
Instead, you can attach it immediately if you create a field of loaded salons and the adapter
IBranchLoadListener iBranchLoadListener;
List<Salon> mSalons = new ArrayList<>();
RecyclerView.Adapter<MySalonAdapter.MyViewHolder> mAdapter;
Use that list in the callback rather than make a new list
if(task.isSuccessful())
{
mSalons.clear();
List<DocumentSnapshot> result = task.getResult();
iOnLoadCountSalon.onLoadCountSalonSuccess(result.size());
for(DocumentSnapshot salonSnapShot : result)
{
Salon salon = salonSnapShot.toObject(Salon.class);
mSalons.add(salon);
}
iBranchLoadListener.onBranchLoadSuccess(mSalons);
}
And then initialize and attach your adapter immediately within the onCreate or init methods rather than wait for the callback
Within onBranchLoadSuccess you should notify the adapter that it needs updated

Scroll to a specific item in recyclerview when clicked on another recyclerView item

I have two recycler view one horizontal and one vertical
In my horizontal recycler view, there are categories and in vertical, there is items list. So I need to do that when I click on any category my vertical recycler view scroll to that specific item
Attaching the screenshot in the link - https://ibb.co/n67WdRn
https://ibb.co/P5CrjnH
I have tried using intent and it works but it starts a new activity
Please help
Mainactivity.java
package com.example.myapplication;
public class MainActivity extends AppCompatActivity {
DatabaseReference reference;
ArrayList<dish> list;
private static final String TAG = "MainActivity";
private ArrayList<String> mCategory = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCategory();
menu();
}
private void getCategory(){
Log.d(TAG, "Preparing Categories");
mCategory.add("Vagetables");
mCategory.add("Indian Bread");
mCategory.add("Paranthas");
mCategory.add("Starters");
mCategory.add("Snacks");
mCategory.add("Salad");
mCategory.add("Noodles");
mCategory.add("Sandwiches");
mCategory.add("Rice");
mCategory.add("Soups");
mCategory.add("Beverages");
mCategory.add("Yoghurt");
mCategory.add("Papad");
initRecyclerView();
}
private void initRecyclerView(){
Log.d(TAG, "init RecyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, mCategory);
recyclerView.setAdapter(adapter);
}
private void menu(){
list = new ArrayList<dish>();
Log.d(TAG, "recycler MenuView : Firebase Initialized");
FirebaseApp.initializeApp(this);
reference = FirebaseDatabase.getInstance().getReference().child("dishes");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange : called");
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Log.d(TAG,"Adding Menu");
dish p = dataSnapshot1.getValue(dish.class);
Log.d(TAG, "called : " + p);
Log.d(TAG, " : " + dataSnapshot + " : " + dataSnapshot1);
list.add(p);
}
getmenu();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, " Opps....Somethinf Went wrong!", Toast.LENGTH_LONG).show();
}
});
}
private void getmenu(){
Log.d(TAG,"Setting adapter");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
RecyclerView recyclerMenuView = findViewById(R.id.recyclerMenuView);
recyclerMenuView.setLayoutManager(linearLayoutManager);
MenuAdapter adapter = new MenuAdapter(MainActivity.this, list);
recyclerMenuView.setAdapter(adapter);
}
}
RecyclerViewAdapter.java - Category recyclerview (Click on this item)
package com.example.myapplication;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
#NonNull
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mCategory = new ArrayList<>();
private Context context;
public RecyclerViewAdapter(Context context, ArrayList<String> category) {
this.context = context;
mCategory = category;
}
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG ,"On Create View Holder: called");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "OnBindViewHolder: called");
holder.category.setText(mCategory.get(position));
holder.category.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"onClick : Clicked on Text" + mCategory.get(position));
Toast.makeText(context, mCategory.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mCategory.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView category;
public ViewHolder(#NonNull View itemView) {
super(itemView);
category = itemView.findViewById(R.id.category);
}
}
}
MenuAdapter.java - Scroll the item rom this recycler view
package com.example.myapplication;
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.menuViewHolder>{
Context context;
ArrayList<dish> dishes;
public MenuAdapter(Context c , ArrayList<dish> p)
{
context = c;
dishes = p;
}
#NonNull
#Override
public menuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG ,"On Create View Holder: called");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
return new MenuAdapter.menuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull menuViewHolder holder, final int position) {
holder.dishname.setText(dishes.get(position).getDishname());
holder.dishrate.setText(dishes.get(position).getDishrate());
Picasso.get().load(dishes.get(position).getDishImage()).placeholder(R.drawable.ic_launcher_background).into(holder.dishImage);
boolean flag = dishes.get(position).getPermission();
if (flag){
Log.d(TAG," recommended : " + dishes.get(position).getDishname());
holder.recommended.setVisibility(View.VISIBLE);
}
else{
holder.recommended.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return dishes.size();
}
class menuViewHolder extends RecyclerView.ViewHolder {
TextView dishname, dishrate, recommended;
ImageView dishImage;
public menuViewHolder(#NonNull View itemView)
{
super(itemView);
dishname = (TextView) itemView.findViewById(R.id.dishname);
dishrate = (TextView) itemView.findViewById(R.id.dishrate);
dishImage = (ImageView) itemView.findViewById(R.id.dishImage);
recommended = (TextView) itemView.findViewById(R.id.recommended);
}
}
}
Try using RecyclerView's scrollTo(position) or smoothScrollTo(position)

Passing data from RecyclerView.Adapter to fragment onClick

I'm trying to figure out how to get data from a clicked item in a RecyclerView to a listview in a Fragment. I can't seem to figure out how to do this, as I can't get my bundle to work.
I've tried various solutions offered here on Stackoverflow, but none of them have worked. I have managed to get the info from the recyclerview, but I am stuck trying to figure out how I can pass it to the fragment. Can someone please help me?
The Adapter class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
private Context context;
ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list){
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());
//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String foods = list.get(position).getName();
String carbo = list.get(position).getCarbohydrates();
String protein = list.get(position).getProtein();
String fats = list.get(position).getFats();
Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView foods, carbo, fats, protein;
public ViewHolder(View itemView) {
super(itemView);
carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);
}
}
}
The Fragment where the data comes from:
public class TrackingFragment extends Fragment {
DatabaseReference databaseReference;
ArrayList<FoodActivity> list;
RecyclerView recyclerView;
SearchView searchView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tracking, container, false);
databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
recyclerView = view.findViewById(R.id.rv);
searchView = view.findViewById(R.id.searchFood);
return view;
}
#Override
public void onStart() {
super.onStart();
if(databaseReference != null){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
list.add(ds.getValue(FoodActivity.class));
}
FoodAdapter adapter = new FoodAdapter(list);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if(searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str){
ArrayList<FoodActivity> searchList = new ArrayList<>();
for(FoodActivity object : list){
if(object.getName().toLowerCase().contains(str.toLowerCase())){
searchList.add(object);
}
}
FoodAdapter foodAdapter = new FoodAdapter(searchList);
recyclerView.setAdapter(foodAdapter);
}
}
And the class where it needs to go:
public class FoodFragment extends Fragment {
ImageButton addFood;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container, false);
addFood = view.findViewById(R.id.addFood);
addFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new TrackingFragment());
fr.addToBackStack(null).commit();
}
});
return view;
}
}
The most simple is to add variables you need to your activity, set their values with onClick() and then retrieve data in other fragment:
in activity:
String foods;
public String getFoods() {
return foods;
}
public void setFoods(String foods) {
this.foods = foods;
}
in adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((YourActivity)getActivity()).setFoods("Any value");
}
});
in destination fragment:
String foods = ((YourActivity)getActivity()).getFoods();
Add an interface to your adapter as follow
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
interface OnClickListener {
void onClick(FoodActivity clickedItem);
}
private OnClickListener mCallback;
private ArrayList<FoodActivity> list;
public FoodAdapter(ArrayList<FoodActivity> list){
this.list = list;
}
public void setOnClickListener(OnClickListener callback) {
mCallback = callback;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item_food, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.foods.setText(list.get(position).getName());
holder.carbo.setText(list.get(position).getCarbohydrates());
holder.protein.setText(list.get(position).getProtein());
holder.fats.setText(list.get(position).getFats());
//Get items from recyclerview when user clicks them. Then send them to FoodFragment
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallback != null)
mCallback.onClick(list.get(position));
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView foods, carbo, fats, protein;
public ViewHolder(View itemView) {
super(itemView);
carbo = itemView.findViewById(R.id.carbo);
protein = itemView.findViewById(R.id.protein);
fats = itemView.findViewById(R.id.fats);
foods = itemView.findViewById(R.id.food);
}
}
}
Android sometimes is a little complicated, when it involves the full stack:
01 RecyclerView Adapter
/** 01. Some Adapter */
public class SomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private WeakReference<Context> mContext;
/** Constructor */
public SomeAdapter(#NonNull Context context) {
this.mContext = new WeakReference<>(context);
}
#NonNull
protected Context getContext() {
return this.mContext.get();
}
/** Call to Activity from within the adapter. */
private void someMethod() {
SomeActivity activity = (SomeActivity) getContext();
synchronized(activity) {activity.showLoginDialog();}
}
}
02 AppCompatActivity
/** 02. Some Activity */
public class SomeActivity extends AppCompatActivity {
#Nullable
private BaseFragment currentFragment = null;
/** Constructor */
public SomeActivity() {}
public void setCurrentFragment(Fragment fragment) {
this.currentFragment = fragment;
}
/** Call to the current Fragment. */
public void someMethod() {
if (currentFragment != null) {
currentFragment.someMethod();
}
}
}
03 Fragment
/** Some Fragment */
public class SomeFragment extends Fragment {
/** Constructor */
public SomeFragment() {}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
((BaseActivity) context).setCurrentFragment(this);
}
#Override
public void onDetach() {
super.onDetach();
((BaseActivity) getActivity()).setCurrentFragment(this);
}
}
To get your data from FoodAdapter to TrackingFragment, you can add TrackingFragment (or an interface it implements, ideally) as a parameter to the FoodAdapter constructor, then use that instance to forward your ViewHolder clicks to TrackingFragment for handling.
To get your data from TrackingFragment to FoodFragment, use the setTargetFragment/onActivityResult pattern for fragment <-> fragment communication. This answer has an example: https://stackoverflow.com/a/13733914/3238938

New fetch data is not show on recycler list when pull down to refresh

I want to implement one code where data will come on Scroll and if the data is add on list then we pull down(SwipeRefreshLayout) the new data will come on that list. In my below code the add on data is coming in response but not come in list? I have read many tutorials like this but data is coming on Swipe refresh but not shown on list. Thank you in advance
public class UpdatesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
SwipeRefreshLayout mSwipeRefreshLayout;
UserSessionManager session;
private List<SuperHero> listSuperHeroes;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public ProgressBar progressBar;
public String user_id;
TextView textView;
FloatingActionButton fab;
public int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_updates, container, false);
session = new UserSessionManager(getActivity());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
user_id = user.get(UserSessionManager.KEY_USER_ID);
// SwipeRefreshLayout
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
getDataFromServer(1);
}
});
return view;
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
fab = (FloatingActionButton)v.findViewById(R.id.fab);
recyclerView = (RecyclerView) v.findViewById(R.id.updatesRecycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
listSuperHeroes = new ArrayList<>();
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter);
textView = (TextView)v.findViewById(R.id.text);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), AddWebPostActivity.class);
startActivity(i);
}
});
getDataFromServer(a);
recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener((LinearLayoutManager) layoutManager) {
#Override
public void onLoadMore(int current_page) {
getDataFromServer(current_page);
}
});
}
public void getDataFromServer(int requestCount) {
Log.e("count",String.valueOf(requestCount));
final String DATA_URL = "https://XYZ.php?username="+user_id + "&page="+requestCount;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mSwipeRefreshLayout.setRefreshing(false);
Log.e("URL___________",DATA_URL);
Log.e("response___________", String.valueOf(response));
parseData(response);
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.getCache().clear();
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setPost_title(json.getString(Config.TAG_POST_TITLE));
superHero.setPost_content(json.getString(Config.TAG_POST_CONTENT));
superHero.setPost_parent(json.getString(Config.TAG_POST_PARENT));
superHero.setPost_date(json.getString(Config.TAG_POST_DATE));
superHero.setPost_date_gmt(json.getString(Config.TAG_POST_DATE_GMT));
superHero.setScheduled_date(json.getString(Config.TAG_SCHEDULED_DATE));
superHero.setTo_ping(json.getString(Config.TAG_IP_ADDRESS));
superHero.setVisit_post(json.getString(Config.TAG_VISIT_POST));
superHero.setUr_id(json.getString(Config.TAG_UR_ID));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
}
/**
* Called when a swipe gesture triggers a refresh.
*/
#Override
public void onRefresh() {
getDataFromServer(1);
}
}
Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
UserSessionManager session;
public String user_id;
public String ur_id;
private Context context;
//String visit;
//List to store all superheroes
List<SuperHero> superHeroes;
//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
super();
//Getting all superheroes
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.web_post, parent, false);
// Session class instance
session = new UserSessionManager(context);
session.checkLogin();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
user_id = user.get(UserSessionManager.KEY_USER_ID);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
//Getting the particular item from the list
final SuperHero superHero = superHeroes.get(position);
holder.tvPostTitle.setText(superHero.getPost_title());
holder.tvPostContent.setText(superHero.getPost_content());
holder.tvPostDateTime1.setText(superHero.getPost_date() +" / " +superHero.getPost_date_gmt());
final String visit = superHero.getVisit_post();
holder.tvVisitPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,VisitWebView.class);
i.putExtra("visitURL",visit);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return superHeroes.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
//Views
public TextView tvPostTitle,tvPostContent,tvPostDateTime1,tvVisitPost;
public ImageButton removeButton;
//Initializing Views
public ViewHolder(final View itemView) {
super(itemView);
tvPostTitle = (TextView) itemView.findViewById(R.id.tvPostTitle);
tvPostContent = (TextView) itemView.findViewById(R.id.tvPostContent);
tvPostDateTime1 = (TextView) itemView.findViewById(R.id.tvPostDateTime1);
tvVisitPost = (TextView) itemView.findViewById(R.id.tvVisitPost);
removeButton = (ImageButton) itemView.findViewById(R.id.removeButton);
}
}
}
use this method
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
getDataFromServer(1);
}
instead of this
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
getDataFromServer(1);
}
});
Please call adapter and pass fresh list data after this line
listSuperHeroes.add(superHero) in parseData(response) function ;
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter)
adapter.notifyDataSetChanged();

Categories

Resources