RecyclerView Adapter notify data changed - android

There is my activity:
public class EventDetailsActivity extends AppCompatActivity {
private Event event;
private ArrayList<User> subscribedUsers;
private RecyclerView mRecyclerView;
private String eventId;
private SubscribedUsersAdapter adapter;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
context = this;
Bundle extras = getIntent().getExtras();
eventId = extras.getString("eventId");
setUpEvent();
}
private void setUpEvent() {
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(eventId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventType = dataSnapshot.child("eventType").getValue().toString();
String description = dataSnapshot.child("description").getValue().toString();
Object object = dataSnapshot.child("startingDate").getValue();
HashMap result = (HashMap) object;
int year = Integer.parseInt(result.get("year").toString());
int month = Integer.parseInt(result.get("month").toString());
int day = Integer.parseInt(result.get("date").toString());
int hour = Integer.parseInt(result.get("hours").toString());
int minute = Integer.parseInt(result.get("minutes").toString());
Date startingDate = new Date(year,month,day,hour,minute,0);
object = dataSnapshot.child("location").getValue();
result = (HashMap) object;
double latitude = Double.parseDouble(result.get("latitude").toString());
double longitude = Double.parseDouble(result.get("longitude").toString());
LatLng location = new LatLng(latitude,longitude);
String userId = dataSnapshot.child("userId").getValue().toString();
String userName = dataSnapshot.child("userName").getValue().toString();
String userPicture = dataSnapshot.child("userPicture").getValue().toString();
subscribedUsers = new ArrayList<User>();
if (dataSnapshot.hasChild("subscribedUsers")) {
mDatabase.child("subscribedUsers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
event = new Event(eventId, eventType,description,startingDate,location,userId, userName, userPicture);
setText();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setText()
{
ImageView mProfilePicture = (ImageView) findViewById(R.id.profilePicture);
if (!EventDetailsActivity.this.isFinishing()) {
Glide
.with(this)
.load(event.getUserPicture())
.into(mProfilePicture);
}
TextView mUserName = (TextView) findViewById(R.id.userName);
mUserName.setText(event.getUserName());
TextView mEventType = (TextView) findViewById(R.id.eventType);
mEventType.setText(event.getEventType());
TextView mDescription = (TextView) findViewById(R.id.description);
mDescription.setText(event.getDescription());
if (!EventDetailsActivity.this.isFinishing()) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(new OnMapReadyCallback()
{
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.clear();
googleMap.addMarker(new MarkerOptions().position(event.getLocation()));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(event.getLocation(),12.0f));
}
});
}
TextView mStartingDate = (TextView) findViewById(R.id.startingDate);
Date startingDate = event.getStartingDate();
String displayText = String.valueOf(startingDate.getYear());
int month = startingDate.getMonth() + 1;
if (month/10 == 0)
{
displayText = displayText + ".0" + month;
}
else
{
displayText = displayText + "." + month;
}
if (startingDate.getDate()/10 == 0)
{
displayText = displayText + ".0" + startingDate.getDate();
}
else
{
displayText = displayText + "." + startingDate.getDate();
}
if (startingDate.getHours()/10 == 0)
{
displayText = displayText + ". 0" + startingDate.getHours();
}
else
{
displayText = displayText + ". " + startingDate.getHours();
}
if (startingDate.getMinutes()/10 == 0)
{
displayText = displayText + ":0" + startingDate.getMinutes();
}
else
{
displayText = displayText + ":" + startingDate.getMinutes();
}
mStartingDate.setText(displayText);
setUpRecyclerView();
subscribe();
}
private void setUpRecyclerView() {
adapter = new SubscribedUsersAdapter(this,subscribedUsers);
mRecyclerView.setAdapter(adapter);
}
private void subscribe()
{
FirebaseAuth mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
final String userId = mAuth.getCurrentUser().getUid();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("name").getValue().toString();
String userPicture = dataSnapshot.child("picture").getValue().toString();
User user = new User(userId, userName, userPicture);
userSubscribe(user);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
userSubscribe(null);
}
}
private void userSubscribe(final User user) {
Button mSubscribeButton = (Button) findViewById(R.id.subscribeButton);
if (user == null)
{
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(EventDetailsActivity.this, getResources().getString(R.string.logInToSubscribe), Toast.LENGTH_LONG).show();
Intent loginIntent = new Intent(EventDetailsActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
});
}
else if (containsUser(subscribedUsers,user) == -1)
{
mSubscribeButton.setText(getResources().getString(R.string.subscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
subscribedUsers.add(user);
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
else
{
mSubscribeButton.setText(getResources().getString(R.string.unsubscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
int position = containsUser(subscribedUsers,user);
subscribedUsers.remove(position);
mDatabase.child("subscribedUsers").removeValue();
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
private int containsUser(ArrayList<User> users, User user)
{
for (int i=0; i<users.size(); ++i)
{
if (users.get(i).getUserId().equals(user.getUserId()))
{
return i;
}
}
return -1;
}
}
And my adapter:
public class SubscribedUsersAdapter extends RecyclerView.Adapter<SubscribedUsersAdapter.ViewHolder>{
private Context context;
private ArrayList<User> items;
public SubscribedUsersAdapter(Context context, ArrayList<User> items) {
this.context = context;
this.items = items;
}
protected static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mProfilePictureView;
public TextView mUserName;
public ViewHolder(View itemView) {
super(itemView);
mProfilePictureView = (ImageView) itemView.findViewById(R.id.profilePictureView);
mUserName = (TextView) itemView.findViewById(R.id.userName);
}
}
#Override
public SubscribedUsersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final User item = items.get(position);
Glide
.with(context)
.load(item.getPicture())
.into(holder.mProfilePictureView);
holder.mUserName.setText(item.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(context, ProfileActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
profileIntent.putExtra("userId", item.getUserId());
context.startActivity(profileIntent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
}
When the activity starts firstly, the data is displayed well in RecyclerView, but if a user subscribes to the event or unsubscribe from it, the RecyclerView will be empty.
I tried with notifyDataSetChanged, notifyItemRangeInserted, notifyItemRangeRemoved, but none of them worked or I didn't use it well. I don't know.
Thanks for your help!

for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
after that just add this line
adapter.notifyDataSetChanged();

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.

Empty Space in Recycler View using Firebase Adapter with View.GONE

So basically I have implemented a fragment for my app using firebase Recycler Adapter. I have searched through out the internet to hide a row in the recycler view without occupying white space. I have applied various people solutions but result is same.
My Fragment code is like this:
public class RequestFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_request, container, false);
mReqList = (RecyclerView) mMainView.findViewById(R.id.req_list);
mRootRef =FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser() !=null)
mCurrent_user_id = mAuth.getCurrentUser().getUid();
if(mCurrent_user_id !=null) {
mReqDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req").child(mCurrent_user_id);
mReqDatabase.keepSynced(true);
}
text = (TextView) mMainView.findViewById(R.id.request_fragment_text);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mReqList.setHasFixedSize(true);
mReqList.setLayoutManager(linearLayoutManager);
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
if(mReqDatabase != null) {
final Query requestQuery = mReqDatabase.orderByChild("request_type");
FirebaseRecyclerAdapter<Request, RequestFragment.ReqViewHolder> firebaseReqAdapter = new FirebaseRecyclerAdapter<Request, RequestFragment.ReqViewHolder>(
Request.class,
R.layout.single_request_layout,
ReqViewHolder.class,
requestQuery
) {
#Override
protected void onDataChanged() {
if(getItemCount() == 0){
text.setText("No New Friend Request");
}
else{
text.setText("");
}
}
#Override
protected void populateViewHolder(final RequestFragment.ReqViewHolder reqViewHolder, final Request req, int i) {
final String list_user_id = getRef(i).getKey();
mAcceptBtn = reqViewHolder.mView.findViewById(R.id.single_req_accept_btn2);
mDeclineBtn = reqViewHolder.mView.findViewById(R.id.single_req_decline_btn);
if (req.getRequest_type().equals("received")) {
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
text.setText("");
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
reqViewHolder.setUserOnline(userOnline);
}
reqViewHolder.setName(userName);
reqViewHolder.setUserImage(userThumb, getContext());
mAcceptBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Friends/" + mCurrent_user_id + "/" + list_user_id + "/date", currentDate);
friendsMap.put("Friends/" + list_user_id + "/" + mCurrent_user_id + "/date", currentDate);
friendsMap.put("Friend_req/" + mCurrent_user_id + "/" + list_user_id, null);
friendsMap.put("Friend_req/" + list_user_id + "/" + mCurrent_user_id, null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
reqViewHolder.mView.setVisibility(View.INVISIBLE);
} else {
String error = databaseError.getMessage();
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
});
mDeclineBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Friend_req/" + mCurrent_user_id + "/" + list_user_id, null);
friendsMap.put("Friend_req/" + list_user_id + "/" + mCurrent_user_id, null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
reqViewHolder.mView.setVisibility(View.INVISIBLE);
} else {
String error = databaseError.getMessage();
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
reqViewHolder.Invisible();
text.setText("No New Friend Request");
}
}
};
mReqList.setAdapter(firebaseReqAdapter);
}
}
public static class ReqViewHolder extends RecyclerView.ViewHolder {
View mView;
public ReqViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setStatus(String status) {
TextView fragmentStatus = mView.findViewById(R.id.request_fragment_text);
fragmentStatus.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.req_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.req_single_image);
Picasso.get().load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.req_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
public void Invisible(){
mView.setVisibility(View.INVISIBLE);
}
}
}
My fragment in the app is looking like this:
Can anyone help me how to get rid of this white space?

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.

Android - Firebase on data change refreshes the page

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

FATAL EXCEPTION: main, java.lang.NullPointerException: Attempt to invoke virtual method

I am beginner at Android app development and I have created a chat app using Firebase database. I am using two Android phones to test the app, Android Samsung 4.4.2 API 19 and Samsung 5.0.1 API 21. The app used to work fine on both phones. I added some lines in the CharActivity for notification purpose, I ran the app, it worked fine on Android Samsung 4.4.2 API 19, but crashes on Samsung 5.0.1 API 21 at the lunch. So I undo all the changes I made until the point where my app was working fine on Samsung 5.0.1 API 21. But the surprise is it still crashes!
Now I am facing a problem with the Samsung 5.0.1 API 21. Every time I run the app it crashes at the lunch, and here is the problem I get.
FATAL EXCEPTION: main
Process: com.example.maalialabdulhafith.nfc_mac, PID: 30357
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Please note that my other Android Samsung 4.4.2 API 19 works fine and doesn't crash.
FriendsFragment Class (Where all my friends are listed)
public class FriendsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.friends_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(
Friends.class,
R.layout.users_single_layout,
FriendsViewHolder.class,
mFriendsDatabase
) {
#Override
protected void populateViewHolder(final FriendsViewHolder friendsViewHolder, Friends friends, int i) {
//friendsViewHolder.setDate(friends.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
final String userStatus = dataSnapshot.child("status").getValue().toString(); // I added this
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.setUserStatus(userStatus); //<== if you want to show status instead of date
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", list_user_id);
startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(friendsRecyclerViewAdapter);
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
/*public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(date);
}*/
//if you want to display the statuse instead of the date, activite this and comment setDate method
public void setUserStatus(String status) {
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}
Chat Class
public class ChatActivity extends AppCompatActivity {
// user id whom we want to chat with
private String mChatUser;
private DatabaseReference mRootRef;
private TextView mTitleView;
private TextView mLastSeenView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private ImageButton mChatAddBtn;
private ImageButton mChatSendBtn;
private EditText mChatMessageView;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout; // For Pagination
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager mLinearLayout;
private MessageAdapter mAdapter;
// For Pagination
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private int itemPos = 0;
private String mLastKey = "";
private String mPrevKey = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat2);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mChatUser = getIntent().getStringExtra("user_id");
String userName = getIntent().getStringExtra("user_name");
getSupportActionBar().setTitle(userName);
// to display the image in the bar
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = inflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
// ---- Custom Action bar Items ----
mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mLastSeenView = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(custom_bar_image);
//mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_btn);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mAdapter = new MessageAdapter(messagesList);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout); // pagenation
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
mMessagesList.setAdapter(mAdapter);
loadMessages();
mTitleView.setText(userName);
// showing last time was seen
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
if(online.equals("true")) {
mLastSeenView.setText("Online");
} else {
GetTimeAgo getTimeAgo = new GetTimeAgo();
long lastTime = Long.parseLong(online);
String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
mLastSeenView.setText(lastSeenTime);
}
//CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.custom_bar_image);
//Picasso.with(i).load(image).placeholder(R.drawable.default_avatar).into(userImageView);
//Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen", false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Chat/" + mCurrentUserId + "/" + mChatUser, chatAddMap);
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
// Swipe/Pull to Refresh for Android RecyclerView
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
itemPos = 0;
loadMoreMessages();
}
});
}
// ------------------ LOAD More Messages ------------------
private void loadMoreMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!mPrevKey.equals(messageKey)){
messagesList.add(itemPos++, message);
} else{
mPrevKey=mLastKey;
}
if (itemPos == 1){
mLastKey = messageKey;
}
Log.d("TOTALKEYS", "Last Key: " + mLastKey + "| Prev Key: " + mPrevKey + "| Message Key: " + messageKey );
mAdapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
mLinearLayout.scrollToPositionWithOffset(10,0);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ------------------ LOAD Messages ------------------
private void loadMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
itemPos++;
if (itemPos == 1){
String messageKey = dataSnapshot.getKey();
mLastKey = messageKey;
mPrevKey = messageKey;
}
messagesList.add(message);
mAdapter.notifyDataSetChanged();
mMessagesList.scrollToPosition(messagesList.size () -1);
mRefreshLayout.setRefreshing(false);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendMessage() {
String message = mChatMessageView.getText().toString();
if(!TextUtils.isEmpty(message)){
String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();
String push_id = user_message_push.getKey();
Map messageMap = new HashMap();
messageMap.put("message", message);
messageMap.put("seen", false);
messageMap.put("type", "text");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from", mCurrentUserId);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.setText("");
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
}
What doesn't make sense to me is, how does it run on one device and doesn't on other? I would appreciate a detailed answer. Thanks in advance!
Acknowledgment: I have learned this code from the amazing TVAC Studio on Youtube.
The user is not signed-in.
Change your code to the following
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null && !firebaseUser.getUid().isEmpty()) {
// all OK
} else {
// repeat the authentication process again
}
As explained by tim4dev, you havent logged in using any specific user. If you havent created a user, go to the firebase console and allow a signup type. They are like email and password auth, phone number auth, anonymous, etc. Once you have enabled one of the options, you can sign up using the auth class and sign in / login afterwards. Once you login with a user account on a device, only then will the
mCurrent_user_id = mAuth.getCurrentUser().getUid();
statement work and return a non-null id.
Hope it solves the problem.

Categories

Resources