My database structure
I am trying to create an activity where I can display all the logs. Just timestamp and the log message. I have tried with firebaseUI and adapter but I can't get the data to show. Best I have done was to post same last log in all positions. This is what I have so far but no success. I am new to firebase and all I need is to display the logs in a list. It can be lisView or recyclerView. If anyone can help me with code or example. Thank you.
Database structure is | "logs" node / userId / logId / fields |
public class LogActivity extends AppCompatActivity {
private static final String TAG = "LogActivity";
private static final int ACTIVITY_NUM = 3;
//widgets
private Context mContext = LogActivity.this;
private RecyclerView mLogRecycleView;
private TextView timeStamp, log;
//firebase
private DatabaseReference mLogDatabase;
private FirebaseAuth mAuth;
//adapter
private FirebaseRecyclerAdapter adapter;
//vars
private String mCurrentUserID, logID;
List<AppLogs> logsList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
Log.d(TAG, "onCreate: Started");
mCurrentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mLogRecycleView = findViewById(R.id.recyclerList);
mLogDatabase = FirebaseDatabase.getInstance().getReference().child("logs").child(mCurrentUserID);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mLogRecycleView.setHasFixedSize(true);
mLogRecycleView.setLayoutManager(linearLayoutManager);
firebaseListAdapter();
mLogRecycleView.setAdapter(adapter);
setupBottomNavigationView();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private void firebaseListAdapter() {
Log.d(TAG, "firebaseListAdapter: started");
Query logQuery = mLogDatabase.orderByChild("time");
FirebaseRecyclerOptions<AppLogs> options =
new FirebaseRecyclerOptions.Builder<AppLogs>()
.setQuery(logQuery, AppLogs.class).build();
adapter = new FirebaseRecyclerAdapter<AppLogs, LogViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final LogViewHolder holder, int position, #NonNull AppLogs model) {
Log.d(TAG, "onBindViewHolder: started");
//get the ID of the messages
//final String logID = getRef(position).getKey();
//Log.d(TAG, "onBindViewHolder: logID : " + logID);
Query logQuery = mLogDatabase;
logQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singData : dataSnapshot.getChildren()) {
//AppLogs logs = dataSnapshot.getValue(AppLogs.class);
Log.d(TAG, "onChildAdded: log:==== " + singData.child("log").getValue());
//Log.d(TAG, "onChildAdded: log_ID:==== " + logs.getLog_id());
String log = singData.child("log").getValue().toString();
// String timeStamp = Long.toString(logs.getTime());
//
holder.setLog(log);
// holder.setTimeStamp(timeStamp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public LogViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: create users view holder: ");
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_log_list_view, parent, false);
return new LogViewHolder(view);
}
};
}
public static class LogViewHolder extends RecyclerView.ViewHolder {
View mView;
public LogViewHolder(View itemView) {
super(itemView);
this.mView = itemView;
}
public void setLog(String log) {
TextView tvLog = mView.findViewById(R.id.tvLog);
tvLog.setText(log);
}
public void setTimeStamp(String timeStamp) {
TextView tvTimeStamp = mView.findViewById(R.id.tvTimeStamp);
tvTimeStamp.setText(timeStamp);
}
}
/*
*BottomNavigationView Setup
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
and my log model class
package com.logistics.alucard.socialnetwork.Models;
public class AppLogs {
private String log, log_id;
private long time;
public AppLogs(String log, String log_id, long time) {
this.log = log;
this.log_id = log_id;
this.time = time;
}
public AppLogs() {
}
public String getLog() {
return log;
}
public void setLog(String log) {
this.log = log;
}
public String getLog_id() {
return log_id;
}
public void setLog_id(String log_id) {
this.log_id = log_id;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
I manage to figure it out! Thank you for your help. Still a bit confusing how to
build queries but I'll try to get better :)
This is my solution to the firebase retrieve data:
protected void onBindViewHolder(#NonNull final LogViewHolder holder, int position, #NonNull AppLogs model) {
Log.d(TAG, "onBindViewHolder: started");
//get the ID of the messages
final String logID = getRef(position).getKey();
//Log.d(TAG, "onBindViewHolder: logID : " + logID);
Query logQuery = mLogDatabase;
logQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//AppLogs appLogs = dataSnapshot.getValue(AppLogs.class);
//Log.d(TAG, "onDataChange: logs:---------" + dataSnapshot.child(logID).child("log").getValue());
String log = dataSnapshot.child(logID).child("log").getValue().toString();
String timeStamp = dataSnapshot.child(logID).child("time").getValue().toString();
Log.d(TAG, "onDataChange: logs:--------------" + log);
holder.setLog(log);
holder.setTimeStamp(timeStamp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I do have a total price in adapter OnBindViewHolder method how to send that data back to CartActivity to assign set text on the TextView in the CartActivity . should i go for Bundle to send the data to activity from the adapter or is there any other way to do it . thanks
My adapter code which extends FirestoreAdapter
public class ItemCartRecyelerAdapter extends
FirestoreAdapter<ItemCartRecyelerAdapter.ViewHolder>{
private static final String TAG = "ItemRecyelerAdapter";
private int TotalPrice = 0;
private Context context;
public interface OnItemSelectedListener {
void OnItemSelected(DocumentSnapshot item);
}
private OnItemSelectedListener mListener;
public ItemCartRecyelerAdapter(Query query, OnItemSelectedListener listener) {
super(query);
mListener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.item_cart_adapter,parent,false));
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(getSnapshot(position), mListener);
Attachment attachment = getSnapshot(position).toObject(Attachment.class);
TotalPrice += attachment.getItem_price() * attachment.getItem_quantity();
Log.d(TAG, "onBindViewHolder: FinalCrossToatal: " + TotalPrice)
}
public void deleteItem(int position){
getSnapshot(position).getReference().delete();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView item_name, item_company, item_price, discount_price, discount;
ImageView item_image, subtract_image;
ElegantNumberButton quantityPicker;
int TotalPrice = 0 ;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.itemImageView);
item_company = itemView.findViewById(R.id.item_company);
item_price = itemView.findViewById(R.id.item_price);
item_name = itemView.findViewById(R.id.item_name);
quantityPicker = itemView.findViewById(R.id.quantityPicker);
subtract_image = itemView.findViewById(R.id.subtract_image);
discount_price = itemView.findViewById(R.id.item_discount_price);
discount = itemView.findViewById(R.id.discount);
}
public void bind(final DocumentSnapshot snapshot, final OnItemSelectedListener listener) {
final Attachment attachment = snapshot.toObject(Attachment.class);
Resources resources = itemView.getResources();
TotalPrice += (attachment.getItem_price() * attachment.getItem_quantity());
Log.d(TAG, "bind: Totalss1 = " + TotalPrice);
item_name.setText(attachment.getItem_name());
item_company.setText(attachment.getItem_brand());
discount.setText(String.valueOf(attachment.getItem_discount()) + "%\noff");
quantityPicker.setNumber(String.valueOf(attachment.getItem_quantity()));
if (attachment.getItem_discount() != null && attachment.getItem_discount() != 0) {
subtract_image.setVisibility(View.VISIBLE);
discount_price.setVisibility(View.VISIBLE);
discount.setVisibility(View.VISIBLE);
Integer discountedPrice = attachment.getItem_price() * attachment.getItem_discount() / 100;
Integer priceDiscounted = attachment.getItem_price() - discountedPrice;
discount_price.setText(String.valueOf(priceDiscounted));
}
Log.d(TAG, "bind: Urs: " + attachment.getUrls());
for (Map.Entry<String, String> result : attachment.getUrls().entrySet()) {
String key = result.getKey();
String value = result.getValue();
Log.d(TAG, "bind: Urls+valuew" + key + value);
//Load Image
Glide.with(item_image.getContext())
.load(value)
.into(item_image);
}
quantityPicker.setRange(0, 10);
quantityPicker.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
#Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
Log.d(TAG, "onValueChange: postion " + attachment.getItem_id());
Log.d(TAG, String.format("oldValue: %d newValue: %d", oldValue, newValue));
passData(newValue, attachment.getItem_id(), oldValue);
}
private void passData(int newValue, String item_id, int oldValue) {
// Go to the details page for the selected restaurant
//sharing to seperate cart node in store
if (newValue == 0) {
FirebaseFirestore updateQ = FirebaseFirestore.getInstance();
DocumentReference CartREf = updateQ.collection("Cart")
.document(item_id);
CartREf.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Succed to quantity");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Failed to change cart");
}
});
FirebaseFirestore dQ = FirebaseFirestore.getInstance();
DocumentReference QuanityRef = dQ.collection("fruits & vegetables")
.document("UyGXpk2n1A6mHsUcYjCi")
.collection("Organic Fruits")
.document(item_id);
QuanityRef.update("item_quantity", newValue).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Success updated item_quanity in Products");
}
});
}
Log.d(TAG, "passData: new update StrARTED");
FirebaseFirestore updateQ = FirebaseFirestore.getInstance();
DocumentReference CartREf = updateQ.collection("Cart")
.document(item_id);
CartREf.update("item_quantity", newValue).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Succed to quantity");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Failed to change cart");
}
});
Log.d(TAG, "passData: new update StrARTED");
FirebaseFirestore dQ = FirebaseFirestore.getInstance();
DocumentReference QuanityRef = dQ.collection("fruits & vegetables")
.document("UyGXpk2n1A6mHsUcYjCi")
.collection("Organic Fruits")
.document(item_id);
QuanityRef.update("item_quantity", newValue).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: Succed to quantity");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Failed to change cart");
}
});
}
});
int items_price = attachment.getItem_price() * attachment.getItem_quantity();
item_price.setText("INR " + items_price + "Rs");
//Click Listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.OnItemSelected(snapshot);
}
}
});
}
}
}
this is the method:
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(getSnapshot(position), mListener);
Attachment attachment = getSnapshot(position).toObject(Attachment.class);
TotalPrice += attachment.getItem_price() * attachment.getItem_quantity();
Log.d(TAG, "onBindViewHolder: FinalCrossToatal: " + TotalPrice)
Using Interface to communicate from Recyclerviewadapter with the activity.
Create interface, and activity implements this interface.
public interface OnItemClick {
void onClick (String value);
}
When you create adapter (last parameter is this interface)
public class MainActivity extends AppCompatActivity implements OnItemClick {
recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData, this);
recyclerView.setAdapter(recycleAdapter);
#Override
void onClick (String value){
//Use the data in Activity
}
// In Adapter
private OnItemClick mCallback;
RecycleAdapter(Context context,List<HashMap<String, String>> onlineData,OnItemClick listener){
this.onlineData = onlineData;
this.context = context;
this.mCallback = listener;
}
....
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(getSnapshot(position), mListener);
Attachment attachment = getSnapshot(position).toObject(Attachment.class);
TotalPrice += attachment.getItem_price() * attachment.getItem_quantity();
Log.d(TAG, "onBindViewHolder: FinalCrossToatal: " + TotalPrice)
mCallback.onClick(TotalPrice);
Try Bundle to send the data in onBindViewHolder
SomeActivity activity= new SomeActivity ();
Bundle args = new Bundle();
args.putInt("totalPrice ", TotalPrice );
fragment.setArguments(args);
I'm making a messaging app for school, I'm trying to make the messages coming from the user align to the right and the messages from others align left.
I've been looking online to try and figure out how to do it, but I don't understand any of them well enough to apply them. I was hoping for some help with applying any option to my app.
SubjectGroupPage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_group_page);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
rvMessagesSubjectGroupPage.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, true));
final ArrayList<MessageObj> messages = new ArrayList<>();
ArrayList<MessageObj> messagesAdap = readMessages(rvMessagesSubjectGroupPage, messages);
MessageAdapter adapter = new MessageAdapter(messagesAdap);
rvMessagesSubjectGroupPage.setAdapter(adapter);
}
public ArrayList<MessageObj> readMessages(final RecyclerView rv, final ArrayList<MessageObj> messages) {
db.collection("messagesIT")
.orderBy("Timesent", Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String message = document.getString("Message");
String senderName = document.getString("SenderName");
String sender = document.getString("Sender");
Timestamp timesent = document.getTimestamp("Timesent");
MessageObj mess;
mess = new MessageObj(message, sender, senderName, timesent);
messages.add(mess);
Log.d(TAG, "mmmmm: " + mess.getMessage());
Log.d(TAG, "sssss: " + mess.getSender());
Log.d(TAG, "ttttt:" + mess.getTimesent());
showToast("b");
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showToast("There has been an error, please try again later.");
Log.d(TAG, "Error: " + e);
}
});
return messages;
}
MessageAdapter.java
public class MessageAdapter extends
RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private ArrayList<MessageObj> listdata;
private FirebaseAuth currentUser = FirebaseAuth.getInstance();
private boolean fromCurrentUser = true;
public static final String MyPREFERENCES = "MyPrefs";
private static String userObject = "";
private static final String TAG = "MessageAdapter.java";
public MessageAdapter(ArrayList<MessageObj> listdata) {
this.listdata = listdata;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView sender;
public TextView message;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
this.sender = (TextView) itemView.findViewById(R.id.sender);
this.message = (TextView) itemView.findViewById(R.id.message);
linearLayout = (LinearLayout) itemView.findViewById(R.id.listLayout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MessageObj myListData = listdata.get(position);
holder.sender.setText(listdata.get(position).getSenderName());
holder.message.setText(listdata.get(position).getMessage());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "click on item: " + myListData.getSender(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
TextView sender;
TextView message;
LinearLayout linearLayout;
return viewHolder;
}
#Override
public int getItemCount() {
return listdata.size();
}
}
MessageObj.java
public class MessageObj {
private String message;
private String sender;
private String senderName;
private Timestamp timesent;
private boolean isCurrentUser;
public MessageObj() {}
public MessageObj(String message, String sender, String senderName, Timestamp timesent) {
this.message = message;
this.sender = sender;
this.senderName = senderName;
this.timesent = timesent;
}
public String getMessage() { return message; }
public String getSender() { return sender; }
public String getSenderName() { return senderName; }
public Timestamp getTimesent() { return timesent; }
Firstly, I've looked into the existing questions that discuss similar issues as mine. Primarily this answer is the closet to the issue I'm having --> Link. I didn't see any solutions that fit my issue.
I've attached below the code for both my HomeFragment & HomeListAdapter. I've done some research as some say I shouldn't do the firebase database calls within the bindviewholder, but Firebase quick start database example is what I am following so if any firebase android engineers might give me some direction that would be great.
When I click add on my Edit Recipe Fragment. After the upload has completed it goes to the home fragment. The confusion I have is every other adapter I have in the app has the correct behavior. It only adds one recipe (only one is ever added at a time is the expected behavior).
HomeFragment
package com.irondigitalmedia.keep;
import java.util.ArrayList;
public class HomeFragment extends BaseFragment {
private static final String TAG = HomeFragment.class.getSimpleName();
private ArrayList<Recipe> mRecipeList;
private ArrayList<String> mRecipeIds;
private RecyclerView HomeRecyclerView;
private HomeListAdapter adapter;
private LinearLayoutManager LLM;
private Context mContext;
private FirebaseDatabase database;
private DatabaseReference myRef;
private Recipe mRecipe;
private User mUser;
private int likeCounter = 0;
private MainActivity mainActivity;
private BaseActivity baseActivity;
private Toolbar toolbar;
private ProgressBar progressBar;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
mContext = view.getContext();
mRecipeList = new ArrayList<>();
mRecipeIds = new ArrayList<>();
HomeRecyclerView = view.findViewById(R.id.frag_search_rv);
HomeRecyclerView.addItemDecoration(new SpacesItemDecoration(8));
LLM = new LinearLayoutManager(getContext());
HomeRecyclerView.setLayoutManager(LLM);
adapter = new HomeListAdapter(mContext, mRecipeList, mUser);
HomeRecyclerView.setAdapter(adapter);
mainActivity = (MainActivity) view.getContext();
mainActivity.mMainNav.setSelectedItemId(R.id.nav_home);
toolbar = mainActivity.findViewById(R.id.main_toolbar);
toolbar.setTitle("Home");
mainActivity.setSupportActionBar(toolbar);
if(savedInstanceState != null){
Log.e(TAG, "onCreateView: savedInstanceState is null");
}else{
LoadRecipes();
}
return view;
}
private void LoadRecipes() {
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
myRef.child(Constants.DATABASE_ROOT_FOLLOWING).child(getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String key = dataSnapshot.getKey();
Log.i(TAG, "onChildAdded: key is = " + key);
if(key!=null){
Log.i(TAG, "onChildAdded: key is not null ");
myRef.child(Constants.DATABASE_ROOT_USERS_RECIPES).child(key).limitToFirst(5).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
mRecipe = dataSnapshot.getValue(Recipe.class);
// [START_EXCLUDE]
// Update RecyclerView
mRecipeIds.add(dataSnapshot.getKey());
mRecipeList.add(mRecipe);
adapter.notifyItemInserted(mRecipeList.size() - 1);
// [END_EXCLUDE]
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
mRecipe = dataSnapshot.getValue(Recipe.class);
String recipeKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mRecipeIds.indexOf(recipeKey);
if (commentIndex > -1) {
// Replace with the new data
mRecipeList.set(commentIndex, mRecipe);
// Update the RecyclerView
adapter.notifyItemChanged(commentIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + recipeKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String recipeKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mRecipeIds.indexOf(recipeKey);
if (commentIndex > -1) {
// Remove data from the list
mRecipeIds.remove(commentIndex);
mRecipeList.remove(commentIndex);
// Update the RecyclerView
adapter.notifyItemRemoved(commentIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + recipeKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
mRecipe = dataSnapshot.getValue(Recipe.class);
String recipeKey = dataSnapshot.getKey();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "recipes:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load recipes.",
Toast.LENGTH_SHORT).show();
}
});
}else{
Log.e(TAG, "onChildAdded: Key is null");
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(Constants.SAVED_STATE_HOME,mRecipeList);
}
#Override
public void onStart() {
super.onStart();
getActivity().setTitle("Home");
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
HomeListAdapter
package com.irondigitalmedia.keep.Adapters;
public class HomeListAdapter extends RecyclerView.Adapter<HomeListAdapter.ViewHolder> {
private static final String TAG = HomeListAdapter.class.getSimpleName();
private DatabaseReference mDatabase;
private Context context;
private List<Recipe> mRecipesList;
private MainActivity mainActivity;
private User user;
private int likeCounter = 0;
public HomeListAdapter(Context context, List<Recipe> mRecipesList, User user) {
this.context = context;
this.mRecipesList = mRecipesList;
this.user = user;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_recipes_recipe_item, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
mainActivity = (MainActivity) view.getContext();
return new HomeListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Recipe recipe = mRecipesList.get(position);
SetUserData(holder, position);
holder.tv_recipe_title.setText(mRecipesList.get(position).getTitle());
holder.tv_recipe_prepTime.setText(mRecipesList.get(position).getPrepTime());
Glide.with(context).load(mRecipesList.get(position).getUrl())
.placeholder(R.drawable.ic_loading).thumbnail(0.05f).fitCenter()
.transition(DrawableTransitionOptions.withCrossFade()).centerCrop()
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.into(holder.recipe_thumbnail);
Log.i(TAG, "onBindViewHolder: Database Reference = " +
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES));
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
.child(Constants.DATABASE_ROOT_LIKES).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
likeCounter = (int) dataSnapshot.getChildrenCount();
Log.i(TAG, "onDataChange: ChildrenCount = " + recipe.getTitle() + " " + likeCounter);
holder.tv_like_counter.setText(Integer.toString(likeCounter));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
.child(Constants.DATABASE_ROOT_LIKES).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(getUid())){
holder.like.setLiked(true);
Log.i(TAG, "onDataChange: LIKED RECIPE...");
}else{
Log.i(TAG, "onDataChange: RECIPE IS NOT LIKED...");
holder.like.setLiked(false);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE)){
holder.tv_like_counter.setText(String.valueOf(dataSnapshot.child(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE).getValue()));
}else{
// likes do not exist
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.like.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Log.i(TAG, "liked: LIKED");
// Add like
holder.like.setLiked(true);
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).child(getUid()).setValue("true");
}
#Override
public void unLiked(LikeButton likeButton) {
Log.i(TAG, "unLiked: UNLIKED");
// remove Like
holder.like.setLiked(false);
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).child(getUid()).removeValue();
}
});
}
private void SetUserData(ViewHolder holder, int position) {
mDatabase.child(Constants.DATABASE_ROOT_USERS).child(mRecipesList.get(position).getCreatorId())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
holder.tv_user_username.setText(user.getUsername());
Glide.with(context).load(user.getUrl()).centerCrop().placeholder(R.drawable.ic_loading).into(holder.userPhoto);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return mRecipesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tv_recipe_title, tv_recipe_prepTime, tv_user_username, tv_like_counter;
public ImageView recipe_thumbnail;
public LikeButton like;
public CircleImageView userPhoto;
public LinearLayout user_ll;
public FirebaseAuth mAuth;
public FirebaseDatabase mDatabase;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mainActivity = (MainActivity) itemView.getContext();
mDatabase = FirebaseDatabase.getInstance();
tv_recipe_title = itemView.findViewById(R.id.recipe_item_title);
tv_recipe_prepTime = itemView.findViewById(R.id.recipe_item_time);
recipe_thumbnail = itemView.findViewById(R.id.recipe_item_photo);
like = itemView.findViewById(R.id.recipe_item_image_like);
tv_like_counter = itemView.findViewById(R.id.recipe_item_like_counter);
userPhoto = itemView.findViewById(R.id.recipe_item_user_photo);
tv_user_username = itemView.findViewById(R.id.recipe_item_user_username);
user_ll = itemView.findViewById(R.id.recipe_item_user_linearLayout);
user_ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment pf = new ProfileFragment();
if(pf.isAdded()){
return;
}else{
Bundle bundle = new Bundle();
bundle.putString(Constants.EXTRA_USER_UID,mRecipesList.get(getAdapterPosition()).getCreatorId());
Log.i(TAG, "onClick: Fragment Interaction recipe Creator Id = " + mRecipesList.get(getAdapterPosition()).getCreatorId());
FragmentTransaction ft = mainActivity.getSupportFragmentManager().beginTransaction();
pf.setArguments(bundle);
ft.replace(R.id.main_frame, pf, Constants.FRAGMENT_TAG_PROFILE);
ft.addToBackStack(Constants.FRAGMENT_TAG_PROFILE);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
});
itemView.setOnClickListener(v -> {
RecipeDetailsFragment rd = new RecipeDetailsFragment();
if(rd.isAdded()){
return;
}else{
Bundle bundle = new Bundle();
bundle.putString(Constants.EXTRA_RECIPE_KEY,mRecipesList.get(getAdapterPosition()).getUid());
bundle.putString(Constants.EXTRA_RECIPE_CREATOR_ID, mRecipesList.get(getAdapterPosition()).getCreatorId());
Log.i(TAG, "onClick: Fragment Interaction recipe Key is = " + mRecipesList.get(getAdapterPosition()).getUid());
FragmentTransaction ft = mainActivity.getSupportFragmentManager().beginTransaction();
rd.setArguments(bundle);
ft.replace(R.id.main_frame, rd, Constants.FRAGMENT_TAG_RECIPE_DETAILS);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
EditRecipeFragment
package com.irondigitalmedia.keep.Adapters;
public class EditIngredientAdapter extends RecyclerView.Adapter<EditIngredientAdapter.IngredientViewHolder> {
private static final String TAG = EditIngredientAdapter.class.getSimpleName();
private String dataSnapShotKey;
private Context mContext;
private DatabaseReference mDatabaseReference;
private ChildEventListener mChildEventListener;
public List<String> mIngredientIds = new ArrayList<>();
public List<Ingredient> mIngredients = new ArrayList<>();
public EditIngredientAdapter(final Context mContext, DatabaseReference ref) {
this.mContext = mContext;
this.mDatabaseReference = ref;
// Create child event listener
// [START child_event_listener_recycler]
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
dataSnapShotKey = dataSnapshot.getKey();
// A new comment has been added, add it to the displayed list
Ingredient ingredient = dataSnapshot.getValue(Ingredient.class);
// [START_EXCLUDE]
// Update RecyclerView
mIngredientIds.add(dataSnapshot.getKey());
mIngredients.add(ingredient);
notifyItemInserted(mIngredients.size() - 1);
// [END_EXCLUDE]
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
Ingredient newIngredient = dataSnapshot.getValue(Ingredient.class);
String ingredientKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int ingredientIndex = mIngredientIds.indexOf(ingredientKey);
if (ingredientIndex > -1) {
// Replace with the new data
mIngredients.set(ingredientIndex, newIngredient);
// Update the RecyclerView
notifyItemChanged(ingredientIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + ingredientKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String ingredientKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int ingredientIndex = mIngredientIds.indexOf(ingredientKey);
if (ingredientIndex > -1) {
// Remove data from the list
mIngredientIds.remove(ingredientIndex);
mIngredients.remove(ingredientIndex);
// Update the RecyclerView
notifyItemRemoved(ingredientIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + ingredientKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
Ingredient movedIngredient = dataSnapshot.getValue(Ingredient.class);
String ingredientKey = dataSnapshot.getKey();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load comments.",
Toast.LENGTH_SHORT).show();
}
};
ref.addChildEventListener(childEventListener);
// [END child_event_listener_recycler]
// Store reference to listener so it can be removed on app stop
mChildEventListener = childEventListener;
}
#NonNull
#Override
public IngredientViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_item_recipe_ingredient, parent, false);
return new IngredientViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull IngredientViewHolder holder, int position) {
Ingredient ingredient = mIngredients.get(position);
holder.ingred.setText(ingredient.ingredient);
}
#Override
public int getItemCount() {
return mIngredients.size();
}
public class IngredientViewHolder extends RecyclerView.ViewHolder {
public TextView ingred;
public IngredientViewHolder(View itemView) {
super(itemView);
ingred = itemView.findViewById(R.id.recipe_ingredients_tv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Ingredient: " + mIngredients.get(getAdapterPosition()).ingredient, Toast.LENGTH_SHORT).show();
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(mContext, "Long Clicked " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
public void RemoveIngredient(DatabaseReference reference){
reference.removeValue();
}
public void cleanupListener() {
if (mChildEventListener != null) {
mDatabaseReference.removeEventListener(mChildEventListener);
}
}
}
Screenshots:
Go To Search and back to home
Back to home
Attempted solution from Majuran (thank you), but it didn't work. Same result. When adding the list.clear() method to both lists.
In my understanding, One thing is added again in your view. when you come back to the same fragment right? (I got the same issue in my last project)
The problem is in HomeFragment. Same values are adding again in your these lists.
mRecipeList = new ArrayList<>();
mRecipeIds = new ArrayList<>();
so clear it, before adding the listener
myRef = database.getReference();
mRecipeList.clear();
mRecipeIds.clear();
myRef.child(Constants.DATABASE_ROOT_FOLLOWING).child(getUid()).add...
Hope its helpful, Happy coding!!!
I was able to resolve this by putting the database call inside the constructor of the adapter. This is the same practice that is within the example that the firebase team put inside their database example app.
I got a source code of a food delivery app from git. he is parsing a website and displaying the menu items, I guess to see the
instead of this I have created a fire-base database and stored one food item for testing
I want to display my item from the fire-base to the app menu I will show the code of all food item fragment,
package com.example.guanzhuli.foody.HomePage.fragment;
public class AllTabFragment extends Fragment {
private String baseUrl = "http://rjtmobile.com/ansari/fos/fosapp/fos_food_loc.php?city=";
private String TAG = "ALLFOOD";
private StorageReference mStorageRef;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
ArrayList<Food> foods = new ArrayList<>();
private RecyclerView mRecyclerView;
private AllFoodAdapter adapter;
private RecyclerView.LayoutManager layoutManager;
String foodName;
public AllTabFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_tab, container, false);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
Toast.makeText(getActivity(), foodName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Request Data From Web Service
if (foods.size() == 0) {
objRequestMethod();
}
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_all);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new AllFoodAdapter(getActivity(), foods);
adapter.setOnItemClickListener(new AllFoodAdapter.OnRecyclerViewItemClickListener() {
#Override
public void onItemClick(View view, String data) {
Bundle itemInfo = new Bundle();
for (int i = 0; i < foods.size(); i++) {
if (foods.get(i).getId() == Integer.valueOf(data)) {
itemInfo.putInt("foodId", foods.get(i).getId());
itemInfo.putString("foodName", foods.get(i).getName());
// itemInfo.putString("foodName", foodName);
itemInfo.putString("foodCat", foods.get(i).getCategory());
itemInfo.putString("foodRec", foods.get(i).getRecepiee());
itemInfo.putDouble("foodPrice", foods.get(i).getPrice());
itemInfo.putString("foodImage", foods.get(i).getImageUrl());
break;
}
}
FoodDetailFragment foodDetailFragment = new FoodDetailFragment();
foodDetailFragment.setArguments(itemInfo);
getActivity().getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out)
.replace(R.id.main_fragment_container, foodDetailFragment)
.addToBackStack(AllTabFragment.class.getName())
.commit();
}
});
mRecyclerView.setAdapter(adapter);
return view;
}
private void objRequestMethod() {
HomePageActivity.showPDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, buildUrl(), null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, jsonObject.toString());
try {
JSONArray foodsJsonArr = jsonObject.getJSONArray("Food");
for (int i = 0; i < foodsJsonArr.length(); i++) {
JSONObject c = foodsJsonArr.getJSONObject(i);
String id = c.getString("FoodId");
String name = c.getString("FoodName");
String recepiee = c.getString("FoodRecepiee");
String price = c.getString("FoodPrice");
String category = c.getString("FoodCategory");
String thumb = c.getString("FoodThumb");
final Food curFood = new Food();
curFood.setCategory(category);
curFood.setName(name);
curFood.setRecepiee(recepiee);
curFood.setPrice(Double.valueOf(price));
curFood.setId(Integer.valueOf(id));
curFood.setImageUrl(thumb);
foods.add(curFood);
// Log.e("Current Food", curFood.getName());
ImageLoader imageLoader = VolleyController.getInstance().getImageLoader();
imageLoader.get(thumb, new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
}
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
curFood.setImage(response.getBitmap());
// Log.e("SET IMAGE", curFood.getName());
adapter.notifyData(foods);
}
}
});
foods.get(i).setImage(curFood.getImage());
}
} catch (Exception e) {
System.out.println(e);
}
HomePageActivity.disPDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG, "ERROR" + volleyError.getMessage());
Toast.makeText(getActivity(), volleyError.getMessage(),
Toast.LENGTH_SHORT).show();
HomePageActivity.disPDialog();
}
});
VolleyController.getInstance().addToRequestQueue(jsonObjReq);
}
private String buildUrl() {
return baseUrl + HomePageActivity.City;
}
}
I got food name from fire-base and stored in the string called "foodname" Now I want to display it in the menu, how can I do it?
if my question is wrong please forgive me, please help me
package com.example.guanzhuli.foody.HomePage.adapter;
public class AllFoodAdapter extends RecyclerView.Adapter<AllHolder> implements
View.OnClickListener {
private Context mContext;
ArrayList<Food> foods;
public String TAG = "ALLFOOD";
//
// public AllFoodAdapter(Context context) {
// mContext = context;
// }
public AllFoodAdapter(Context context, ArrayList<Food> foods) {
mContext = context;
this.foods = foods;
}
#Override
public AllHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.cardview_food, parent, false);
AllHolder allHolder = new AllHolder(v);
v.setOnClickListener(this);
return allHolder;
}
#Override
public void onBindViewHolder(AllHolder holder, int position) {
holder.mTextId.setText(String.valueOf(foods.get(position).getId()));
holder.mTextName.setText(foods.get(position).getName());
holder.mTextPrice.setText(String.valueOf(foods.get(position).getPrice()));
holder.mTextCategory.setText(foods.get(position).getCategory());
holder.mImageView.setImageBitmap(foods.get(position).getImage());
holder.itemView.setTag(foods.get(position).getId());
}
#Override
public int getItemCount() {
return foods.size();
}
public void notifyData(ArrayList<Food> foods) {
// Log.d("notifyData ", foods.size() + "");
this.foods = foods;
notifyDataSetChanged();
}
public static interface OnRecyclerViewItemClickListener {
void onItemClick(View view, String data);
}
private OnRecyclerViewItemClickListener mOnItemClickListener = null;
public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
this.mOnItemClickListener = listener;
}
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, String.valueOf(view.getTag()));
} else {
Log.e("CLICK", "ERROR");
}
}
}
class AllHolder extends RecyclerView.ViewHolder {
NetworkImageView mImage;
ImageView mImageView;
TextView mTextId, mTextName, mTextCategory, mTextPrice;
public AllHolder(View itemView) {
super(itemView);
// mImage = (NetworkImageView) itemView.findViewById(R.id.food_img);
mImageView = (ImageView) itemView.findViewById(R.id.food_img);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextName = (TextView) itemView.findViewById(R.id.food_name);
mTextPrice = (TextView) itemView.findViewById(R.id.food_price);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextCategory = (TextView) itemView.findViewById(R.id.food_category);
}
}
Please help me, because it is an important project for me
If you want to display the strings you have received from firebase in a new activity as a list, you can declare an ArrayList and then add those strings to it and then with an adapter set it to display.
In code it looks something like this:
private ArrayList array;
private ListView listView;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private String curName;
//set them
listView = findViewById(R.id.list1);
array = new ArrayList<String>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
array.add(ds.child("name").getValue(String.class));
}
ArrayAdapter adapter = new ArrayAdapter(Main6Activity.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
stackoverflow was not conceived to get complete code solutions. We can only help you on some point. Other than that, you need to think to use the Food class for read and write values on your db. When you retrive the values, get it as a Food object casting it by method dataSnapshot.getValue("object class");...
In your case you need a code like this:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Food food = snapshot.getValue(Food.class);
//here you need to add the food object to a list and after the for diplay it with adapter.
//for example foodsList.add(food);
}
foodsList.setAdapter(myAdepter); //ecc
}
If you need help, please tell us more
You seem to be loading the food items from the database, and reading the values from them. All that's left to do, is add each item to the foods array, and tell the adapter that its data has changed:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue(String.class);
String foodPrice = snapshot.child("prize").getValue(String.class);
Food food = new Food();
food.setName(name);
food.setPrice(Double.valueOf(price));
foods.add(food);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
I have an adapter class where I am able to load all video from Firebase. But the problem is I can't load both, image and video in one RecyclerView
See what I have done:
I am using toro library to auto play video if your wondering and ExoPlayer to play video
This is my adapter class
public class MainFeedAdapter extends RecyclerView.Adapter<TestAdapter.MyViewHolder> {
private static final String TAG = "MainfeedAdapter";
private List<Photo> moviesList;
private DatabaseReference mReference;
private Context mContext;
private String currentUsername = "";
private int mLayoutResource;
private LayoutInflater mInflater;
private Photo photo;
private MyViewHolder mHolder;
public class MyViewHolder extends RecyclerView.ViewHolder implements ToroPlayer{
static final int LAYOUT_RES = R.layout.main_list;
private ExoPlayerViewHelper helper;
private CircleImageView profile_image;
//private String likeString;
private TextView username,time,caption,likes,comment,stars;
private SquareImageView image;
private LikeButton mHeart,Star;
private UserAccountSettings userAccountSettings = new UserAccountSettings();
private User user = new User();
private StringBuilder users;
private String mLIkeString;
private String mStarString;
private boolean likeByCurrentUSer;
private boolean starbycurrentuser;
private DatabaseReference mNotification;
private ImageView commentBubble;
private Uri mediaUri;
#BindView(R.id.main_post_image2)
PlayerView playerView;
private CardView video;
public MyViewHolder(View view) {
super(view);
profile_image = (CircleImageView)view.findViewById(R.id.post_profile_photo);
username = (TextView) view.findViewById(R.id.main_username);
time = (TextView) view.findViewById(R.id.main_image_time_posted);
caption = (TextView) view.findViewById(R.id.main_image_caption);
likes = (TextView) view.findViewById(R.id.main_likes);
comment = (TextView) view.findViewById(R.id.main_showcomments);
image = (SquareImageView) view.findViewById(R.id.main_post_image);
mHeart = (LikeButton) view.findViewById(R.id.main_heart);
Star = (LikeButton) view.findViewById(R.id.main_star);
stars= (TextView)view.findViewById(R.id.stars);
commentBubble = (ImageView)view.findViewById(R.id.main_comments) ;
mNotification = FirebaseDatabase.getInstance().getReference().child("notification");
mReference = FirebaseDatabase.getInstance().getReference();
ButterKnife.bind(this, itemView);
video = (CardView)view.findViewById(R.id.video_posts);
}
#NonNull
#Override
public View getPlayerView() {
return playerView;
}
#NonNull
#Override
public PlaybackInfo getCurrentPlaybackInfo() {
return helper != null ? helper.getLatestPlaybackInfo() : new PlaybackInfo();
}
#Override
public void initialize(#NonNull Container container, #Nullable PlaybackInfo playbackInfo) {
if (helper == null) {
helper = new SimpleExoPlayerViewHelper(container, this, mediaUri);
}
helper.initialize(playbackInfo);
}
// called from Adapter to setup the media
void bind( Uri item, List<Photo> payloads) {
if (item != null) {
mediaUri = item;
}else {
video.setVisibility(View.GONE);
}
}
#Override
public void play() {
if (helper != null) helper.play();
}
#Override
public void pause() {
if (helper != null) helper.pause();
}
#Override
public boolean isPlaying() {
return helper != null && helper.isPlaying();
}
#Override
public void release() {
if (helper != null) {
helper.release();
helper = null;
}
}
#Override
public boolean wantsToPlay() {
return ToroUtil.visibleAreaOffset(this, itemView.getParent()) >= 0.85;
}
#Override
public int getPlayerOrder() {
return getAdapterPosition();
}
#Override
public void onSettled(Container container) {
}
}
public TestAdapter(List<Photo> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.main_list, parent, false);
mContext = parent.getContext();
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
photo = moviesList.get(position);
mHolder = holder;
holder.users = new StringBuilder();
getCurrentUsername();
getLikesString(mHolder);
getStarString(mHolder);
holder.bind(Uri.parse(photo.getVideo_path()),moviesList);
//get the profile image and username
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_user_account_settings))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
// currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
Log.d(TAG, "onDataChange: found user: "
+ singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.profile_image);
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
holder.userAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
holder.commentBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query userQuery = mReference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.getValue(User.class).getUsername());
holder.user = singleSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private boolean rechedendoflist(int position){
return position == getItemCount() -1;\
}
#Override
public int getItemCount() {
return moviesList.size();
}
public Photo getItem(int position) {
return moviesList.get(position);
}
private void getCurrentUsername(){
Log.d(TAG, "getCurrentUser: ");
Log.d(TAG, "getCurrentUsername: retrieving user account settings");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please help me guys!. Thanks in Advance!.
TheRecyclerView has ability to show items in multiple types.
In your case you can define two ViewType. one for Images and another for Videos.
Search about RecyclerView with multiple view types.
Take a look at here and this.
Also here is a question and answers about it.