Android - Firebase on data change refreshes the page - android

I'm kinda newbie to Android.
I have a recyclerview that I store in Firebase database.
My recyclerview are made of cardviews.
Inside each cardview I have a button that updates the node info in Firebase.
Each time the above is happening, my page refreshes (I guess to load the new data).
My mainactivity code relevant code(called on onCreate) :
private void loadRecyclerViewData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (posts.size() > 0) {
posts.clear();
}
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
//Getting a specific user's information (nickname purposes)
if (post.getSubGenreType().equals(SubGenreString)) {
posts.add(post);
Collections.reverse(posts);
}
}
adapter = new RecyclerAdapter(posts, getApplicationContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my adapter :
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
public static Boolean isAyed = false;
private FirebaseAuth firebaseAuth;
private List<Post> posts;
private Context context;
private String userTryToAyeEmail;
public RecyclerAdapter(List<Post> posts, Context context) {
this.posts = posts;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
firebaseAuth = FirebaseAuth.getInstance();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_card, parent, false);
return new ViewHolder(v);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Post post = posts.get(position);
holder.imageButton.setVisibility(View.GONE);
holder.editText.setVisibility(View.GONE);
String colorString = post.getPostColor();
int color = Color.parseColor(colorString);
int newNumOfLikes = post.getPostLikes();
int currentNumOfLikes = post.getPostLikes();
// holder.cardView.setCardBackgroundColor(color);
holder.textViewHead.setText(post.getPostContent());
holder.textViewNickname.setText(post.getPostNickname());
holder.textViewTimeStamp.setText(post.getPostTimeStamp());
holder.ayeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean userLiked = false;
if (firebaseAuth.getCurrentUser() != null) {
String currentUserEmail = firebaseAuth.getCurrentUser().getEmail();
List<String> currentLikedPost = post.getUserLikedList();
for (int i = 0; i < currentLikedPost.size(); i++) {
if (currentUserEmail.equals(currentLikedPost.get(i))) {
currentLikedPost.remove(i);
int newNumOfLikes = post.getPostLikes() - 1;
updateLikes(post.getId(), newNumOfLikes, post.getPostNickname(), post.getPostTimeStamp(), post.getPostContent(), post.getPostColor(), post.getSubGenreType(), post.getUserLikedList());
userLiked = true;
break;
}
}
if (!userLiked) {
currentLikedPost.add(currentUserEmail);
int newNumOfLikes = post.getPostLikes() + 1;
updateLikes(post.getId(), newNumOfLikes, post.getPostNickname(), post.getPostTimeStamp(), post.getPostContent(), post.getPostColor(), post.getSubGenreType(), post.getUserLikedList());
}
}
}
});
if (firebaseAuth.getCurrentUser() != null) {
String currentUserEmail = firebaseAuth.getCurrentUser().getEmail();
List<String> usersLikedPost = post.getUserLikedList();
for (int i = 0; i < usersLikedPost.size(); i++) {
if (currentUserEmail.equals(usersLikedPost.get(i))) {
holder.ayeButton.setTextColor(Color.parseColor("#FF0000"));
break;
}
}
}
holder.ayeTextView.setText(Integer.toString(newNumOfLikes));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(context, SinglePostActivity.class);
myIntent.putExtra("postID", post.getId());
myIntent.putExtra("postNickname", post.getPostNickname());
myIntent.putExtra("postTimeStamp", post.getPostTimeStamp());
myIntent.putExtra("postContent", post.getPostContent());
myIntent.putExtra("postColor", post.getPostColor());
context.startActivity(myIntent);
}
});
}
private void updateLikes(String id, int newNumOfLikes, String postNickname, String postTimeStamp, String postContent, String postColor, String SubGenre, List<String> userLikedPostList) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("posts").child(id);
Post post = new Post(postColor, postContent, postNickname, postTimeStamp, id, newNumOfLikes, SubGenre, userLikedPostList);
databaseReference.setValue(post);
}
#Override
public int getItemCount() {
return posts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewNickname;
public TextView textViewTimeStamp;
public TextView ayeButton;
public TextView ayeTextView;
public CardView cardView;
public LinearLayout linearLayout;
public EditText editText;
public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewNickname = (TextView) itemView.findViewById(R.id.textViewNickname);
textViewTimeStamp = (TextView) itemView.findViewById(R.id.textViewTimeStamp);
ayeButton = (TextView) itemView.findViewById(R.id.ayeButton);
ayeTextView = (TextView) itemView.findViewById(R.id.ayeTextView);
cardView = (CardView) itemView.findViewById(R.id.cardViewID);
linearLayout = (LinearLayout) itemView.findViewById(R.id.cardLinearLayout);
editText = (EditText) itemView.findViewById(R.id.addCommentEditText);
imageButton = (ImageButton) itemView.findViewById(R.id.addCommentImageButton);
}
}
}
I wish the page to stay in place, how can I do that ??
Thank you all.

Set your adapter in onCreate and notify it from onDataChange
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//initialize
.
.
//set adapter
adapter = new RecyclerAdapter(posts, getApplicationContext());
recyclerView.setAdapter(adapter);
}
private void loadRecyclerViewData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (posts.size() > 0) {
posts.clear();
}
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
//Getting a specific user's information (nickname purposes)
if (post.getSubGenreType().equals(SubGenreString)) {
posts.add(post);
Collections.reverse(posts);
}
}
adapter.notifyDataSetChanged(); //notify
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Related

Import an firebase image when i click it in the recyclerView?

What I've done alone so far is to bring up a activity (recyclerView of the products) when I click ImageView 1.
When I click on the image of recyclerView, my goal is to load the image I clicked on ImageView 1 and save it in DB.
How can I get an image?
this is my product's adapter
#NonNull
#Override
public HolderProductCody onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_product_seller,parent,false);
return new HolderProductCody(view);
}
#Override
public void onBindViewHolder(#NonNull HolderProductCody holder, int position) {
//get data
final ModelProduct modelProduct = productList.get(position);
String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productColor = modelProduct.getProductColor();
String productTpo = modelProduct.getProductTpo();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String SeasonCategory = modelProduct.getProductSeasonCategory();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
//set data
holder.titleTv.setText(title);
holder.SeasonCategoryTv.setText(SeasonCategory);
holder.tpoTv.setText(productTpo);
holder.colorTv.setText(productColor);
holder.originalPriceTv.setText("$"+originalPrice);
if(detailAvailable.equals("true")){
//product is on discount
holder.tpoTv.setVisibility(View.VISIBLE);
holder.colorTv.setVisibility(View.VISIBLE);
}
else{
//product is not on discount
holder.tpoTv.setVisibility(View.GONE);
holder.colorTv.setVisibility(View.GONE);
}
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(holder.productIconIv);
}
catch(Exception e){
holder.productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
Toast.makeText(context, "클릭됨", Toast.LENGTH_SHORT).show();
//addcodylayout(modelProduct);
}
});
}
private void addcodylayout(ModelProduct modelProduct) {
Dialog dialog = new Dialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.activity_cody_product,null);
dialog.setContentView(view);
dialog.show();
//get data
final String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productTpo = modelProduct.getProductTpo();
String productColor = modelProduct.getProductColor();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
final String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(productIconIv);
}
catch(Exception e){
productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
dialog.show();
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public Filter getFilter() {
if(filter==null){
filter = new FilterProduct(this,filterList);
}
return filter;
}
class HolderProductCody extends RecyclerView.ViewHolder{
/*holds views of recyclerview*/
private ImageView productIconIv;
private TextView tpoTv, titleTv, SeasonCategoryTv,colorTv,originalPriceTv;
public HolderProductCody(#NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
tpoTv = itemView.findViewById(R.id.tpoTv);
titleTv = itemView.findViewById(R.id.titleTv);
SeasonCategoryTv = itemView.findViewById(R.id.categorySeasonTv);
colorTv = itemView.findViewById(R.id.colorTv);
originalPriceTv = itemView.findViewById(R.id.originalPriceTv);
}
}
}
this is my product's activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cody_product);
filterProductBtn = findViewById(R.id.filterProductBtn);
productsRv = findViewById(R.id.productsRv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
getSupportActionBar().hide();
firebaseAuth = FirebaseAuth.getInstance();
filterProductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(CodyProductActivity.this);
builder.setTitle("카테고리 선택").setItems(Constants.productCategories1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//get selected item
String selected = Constants.productCategories1[which];
filteredProductsTv.setText(selected);
if (selected.equals("모든 옷")) {
//load all
loadAllProducts();
} else {
//load filtered
loadFilteredProducts(selected);
}
}
}).show();
}
});
}
private void loadFilteredProducts(String selected) {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for(DataSnapshot ds: dataSnapshot.getChildren()){
String productCategory = ""+ds.child("productCategory").getValue();
//if selected category matches product category then add in list
if(selected.equals(productCategory)){
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this,productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this,3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseerror) {
}
});
}
private void loadAllProducts() {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this, productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this, 3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The ID value of ImageView1 is topImages.

NotifyDataSetChanged Recycler view : Cannot call this method while Recycler

I'm making a chat app. I have a recycler view. I use Picasso to download the images of the user and the friend he is chatting with. To not download the image for every message, when I download the first image I just put it into a bitmap and use it every time.
PROBLEM: I can't call NotifyDataSetChanged. I have tried every possible thing I've found on the net.
ERROR :
Cannot call this method while RecyclerView is computing a layout or scrolling android.support.v7.widget.RecyclerView
I have to "manually" refresh the view so that the images are loaded. No problem for the text.
It runs with the Handler but it doesn't even go in the function (so the view isn't refreshed).
Here is my code (everything works except this notifydatasetchanged)
public class ChatActivity extends AppCompatActivity {
private RecyclerView recyclerChat;
private ListMessageAdapter adapter;
private EditText editWriteMessage;
private LinearLayoutManager linearLayoutManager;
private FirebaseAuth mAuth;
private DatabaseReference UserRef, MessageIDREF, UserMessageRef, SendMessageUser;
private List<ChatClass> ListOfChats = new ArrayList<>();
private ImageButton btnSend;
private String currentUserID, currentDateMessage, currentTimeMessage;
private CommunActivit obj = new CommunActivit();
private String FRIENDID;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth=FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
MessageIDREF = FirebaseDatabase.getInstance().getReference().child("Friends");
UserMessageRef = FirebaseDatabase.getInstance().getReference().child("Message").child(obj.getsIDMESSAGE());
btnSend = (ImageButton) findViewById(R.id.btnSend);
editWriteMessage = (EditText) findViewById(R.id.editWriteMessage) ;
FRIENDID = obj.getsIDFRIEND();
mToolbar = (Toolbar) findViewById(R.id.main_app_bar2);
setSupportActionBar(mToolbar);
ActionBar ab = getSupportActionBar();
final String Title = obj.getsFRIENDName();
ab.setTitle(Title);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendMessageToGroupChat();
editWriteMessage.setText("");
}
});
retrievedata();
/*recyclerChat = (RecyclerView)findViewById(R.id.recyclerChat);
adapter = new ListMessageAdapter(this,ListOfChats);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerChat.setLayoutManager(layoutManager);
recyclerChat.setItemAnimator(new DefaultItemAnimator());
recyclerChat.setAdapter(adapter);*/
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerChat = (RecyclerView) findViewById(R.id.recyclerChat);
recyclerChat.setLayoutManager(linearLayoutManager);
adapter = new ListMessageAdapter(this, ListOfChats);
recyclerChat.setAdapter(adapter);
/* editWriteMessage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
recyclerChat.smoothScrollToPosition(adapter.getItemCount());
return false;
}
});*/
}
private void SendMessageToGroupChat() {
String message = editWriteMessage.getText().toString();
String messageKey = UserMessageRef.push().getKey();
if (TextUtils.isEmpty(message)) {
Toast.makeText(this, "Please write a message first", Toast.LENGTH_SHORT).show();
} else {
Calendar calendarDate = Calendar.getInstance();
SimpleDateFormat DateFormat = new SimpleDateFormat("MMM dd, yyyy");
currentDateMessage = DateFormat.format(calendarDate.getTime());
Calendar calendarTime = Calendar.getInstance();
SimpleDateFormat TimeFormat = new SimpleDateFormat("hh:mm a");
currentTimeMessage = TimeFormat.format(calendarTime.getTime());
HashMap<String, Object> groupMessageKey = new HashMap<>();
UserMessageRef.updateChildren(groupMessageKey);
SendMessageUser = UserMessageRef.child(messageKey);
HashMap<String, Object> messageInfoMap = new HashMap<>();
messageInfoMap.put("name", obj.getsUsername());
messageInfoMap.put("message", message);
messageInfoMap.put("date", currentDateMessage);
messageInfoMap.put("time", currentTimeMessage);
messageInfoMap.put("image", obj.getsUserImageLink());
SendMessageUser.updateChildren(messageInfoMap);
}
}
public void retrievedata() {
UserMessageRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) /**** HERE IS THE PROBLEM***/
{
if (dataSnapshot.exists()) {
DisplayMessages(dataSnapshot);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
DisplayMessages(dataSnapshot);
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void DisplayMessages(DataSnapshot dataSnapshot)
{
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
String chatDate = (String) ((DataSnapshot) iterator.next()).getValue();
String chatImage = (String) ((DataSnapshot) iterator.next()).getValue();
String chatMessage = (String) ((DataSnapshot) iterator.next()).getValue();
String chatName = (String) ((DataSnapshot) iterator.next()).getValue();
String chatTime = (String) ((DataSnapshot) iterator.next()).getValue();
ListOfChats.add(new ChatClass(chatName, chatMessage, chatDate + " " + chatTime, chatImage));
adapter.notifyDataSetChanged();
recyclerChat.smoothScrollToPosition(adapter.getItemCount()); /**AUTO SCROLL**/
}
}
class ListMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ChatClass consersation;
private List<ChatClass> List_of_chats;
private CommunActivit obj = new CommunActivit();
private Bitmap BitmapUser;
private Bitmap BitmapFriend;
public ListMessageAdapter(Context context, List<ChatClass> List_of_chats) {
this.context = context;
this.List_of_chats = List_of_chats;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_friend, parent, false);
return new ItemMessageFriendHolder(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_user, parent, false);
return new ItemMessageUserHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final int pos =position;
if (holder instanceof ItemMessageFriendHolder) {
((ItemMessageFriendHolder) holder).txtContent.setText(List_of_chats.get(position).getMessage());
if (BitmapFriend == null) {
Picasso.get().load(List_of_chats.get(position).getImageLink()).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapFriend = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
((ItemMessageFriendHolder) holder).avata.setImageBitmap(BitmapFriend);
}
else
{
((ItemMessageFriendHolder) holder).avata.setImageBitmap(BitmapFriend);
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}
else
{
if (holder instanceof ItemMessageUserHolder) {
((ItemMessageUserHolder) holder).txtContent.setText(List_of_chats.get(position).getMessage());
if (BitmapUser == null) {
Picasso.get().load(List_of_chats.get(position).getImageLink()).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapUser = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
((ItemMessageUserHolder) holder).avata.setImageBitmap(BitmapUser);
} else {
((ItemMessageUserHolder) holder).avata.setImageBitmap(BitmapUser);
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}
}
}
#Override
public int getItemViewType(int position) {
int viewtype = -1;
if (List_of_chats.get(position).getUsername().equals(obj.getsUsername())) {
return 2;
}
else
{
return 1;
}
}
#Override
public int getItemCount() {
return List_of_chats.size();
}
}
class ItemMessageUserHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageUserHolder(View itemView) {
super(itemView);
txtContent = (TextView) itemView.findViewById(R.id.textContentUser);
avata = (CircleImageView) itemView.findViewById(R.id.imageView2);
}
}
class ItemMessageFriendHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageFriendHolder(View itemView) {
super(itemView);
txtContent = (TextView) itemView.findViewById(R.id.textContentFriend);
avata = (CircleImageView) itemView.findViewById(R.id.imageView3);
}
}
It is because you're calling notifyDataSetChanged inside your onBindViewHolder like this:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
...
((ItemMessageFriendHolder) holder).avata.setImageBitmap(BitmapFriend);
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
...
}
You shouldn't force the Adapter to refresh itself before it isn't finished binding the view yet.
So, you need to remove the following code from your onBindViewHolder:
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
then just call notifyDataSetChanged() when you need it. For example, when your dataset is changed.
Try this.
dialeecyclerView.post(new Runnable()
{
#Override
public void run() {
myadapter.notifyDataSetChanged();
}
});
Source - Cannot call this method while RecyclerView is computing a layout or scrolling when try remove item from recyclerview

How to retrieve values from FireBase to JSONArray?

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();
}
});

get key position in onBindViewHolder firebase database

I want to get key position in database.
getting error: getRef(position) : Cannot resolve method 'getRef(int)' on
final String post_key = getRef(position).getKey();
this is my code CustomPostAdapter
public class CustomPostAdapter extends RecyclerView.Adapter<CustomPostAdapter.ViewHolder>{
public List<Spacecraft> userList ;
public Context context ;
private boolean mProcessLike = false ;
private DatabaseReference mDatabaseLike ;
// public ImageView imagePostt ;
public CustomPostAdapter(Context context , List<Spacecraft> userList){
this.userList = userList ;
this.context = context;
}
#NonNull
#Override
public CustomPostAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_posts_item, parent,false);
return new CustomPostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseLike.keepSynced(true);
final String post_key = getRef(position).getKey();
final String name = userList.get(position).getName();
final String image_post = userList.get(position).getImage_post();
final String descrip = userList.get(position).getDescrip();
final String hachatg = userList.get(position).getHachtag();
final String user = userList.get(position).getUser();
final String time = userList.get(position).getTime();
//Text Post
holder.nameText.setText(name);
holder.descripText.setText(descrip);
holder.hachtagText.setText(" " + hachatg);
holder.timeText.setText(" " + time);
//Imgae Post if null set Visibtly Gone to ImageView
if (TextUtils.isEmpty(image_post)){
holder.imagePostt.setVisibility(View.GONE);
}else {
//Image Post
Picasso.with(context).load(image_post).into(holder.imagePostt , new Callback() {
#Override
public void onSuccess() {
holder.imagePostt.setVisibility(View.VISIBLE);
}
#Override
public void onError() {
holder.imagePostt.setVisibility(View.GONE);
}
});
}
//Onclick items
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , ContentActivity.class);
intent.putExtra("NAME_KEY", name);
intent.putExtra("HACHTAG_KEY", hachatg);
intent.putExtra("DESCRIP_KEY", descrip);
intent.putExtra("USER_KEY", user);
intent.putExtra("IMAGE_POST", image_post);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
//Button Like Onclice
holder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
if (mProcessLike){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Chek if user already Like or not
if (dataSnapshot.child(post_key).hasChild(user)){
}else {
mDatabaseLike.child(post_key).child(user).setValue("RandomValue");
mProcessLike = false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public TextView nameText , hachtagText , descripText, urlText , timeText;
public ImageView imagePostt ;
public ImageButton mLikeBtn ;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
nameText = (TextView)mView.findViewById(R.id.text_nameProblem);
hachtagText = (TextView)mView.findViewById(R.id.text_nameUser);
// urlText = (TextView)mView.findViewById(R.id.textUrl);
descripText = (TextView)mView.findViewById(R.id.text_Discription);
timeText = (TextView)mView.findViewById(R.id.timeText);
imagePostt = (ImageView)mView.findViewById(R.id.imagePost);
mLikeBtn = (ImageButton)mView.findViewById(R.id.btnLike);
}
}
}
You should be using FirebaseRecyclerAdapter which has the method getRef(). follow this link to learn how to use it
There are two ways in which you can solve this. The first one would be to store the key as a property in your user object and use:
final String key = userList.get(position).getKey();
And the second one would be to simply use FirebaseRecyclerAdapter instead and call:
mFirebaseRecyclerAdapter.getKey(position);
As explained here by #Puf.

load image and video in recylerview

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.

Categories

Resources