I am having difficulty setting an ImageView with a string download url that is in a user object that came from the firebase storage DB. The method setImage() is saying the Imageview is a null object and this is true as I have tried to debug it and it comes up as null. How can I resolve this. I think it has something to do with the anonymous inner class.
public class DashBoard extends AppCompatActivity {
private FirebaseAuth mAuth;
private ArrayList<String> motivatingMessages;
private Button gymLocations, profile,health;
public ImageView profileImageView;
private TextView welcome;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showProfilePicture();
profileImageView = findViewById(R.id.personalProfile);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
setContentView(R.layout.activity_dash_board);
//getSupportActionBar().setTitle("Welcome To Bodify");
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user != null) {
welcome.setText("User Logged in: ");
welcome.append(user.getUserName());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
gymLocations.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), GymsNearMe.class));
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PersonalProfile.class));
}
});
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(DashBoard.this,Health.class));
}
});
}
public void showProfilePicture() {
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
String image = user.getmImageUrl();
setImage(image);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void setImage(String image) {
Picasso.get().load(image).into(profileImageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logOut) {
mAuth.signOut();
startActivity(new Intent(getApplicationContext(), LogIn.class));
}
return true;
}
}
enter code here
It looks like you are trying to find the view before inflating the layout:
profileImageView = findViewById(R.id.personalProfile);
move that line after the inflation so after the line:
setContentView(R.layout.activity_dash_board);
In other words, the order of the lines should be:
setContentView(R.layout.activity_dash_board);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
profileImageView = findViewById(R.id.personalProfile);
showProfilePicture();
and you do not need to set the mAuth again in the showProfilePicture
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
profileImageView = findViewById(R.id.personalProfile);
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
showProfilePicture();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
try with this order
Related
I have a recycler view on my home page which is showing some posts from my db. I'm passing data like userID, username etc., into the adapter but the profile picture URL is always null inside the adapter. If I try to print it inside the fragment it shows the correct value.
My database structure:
PostRecyclerAdapter:
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
List<PostModel> postList;
Context context;
final private DatabaseReference postRef = FirebaseDatabase.getInstance().getReference("posts");
final private DatabaseReference likeRef = FirebaseDatabase.getInstance().getReference("likes");
final private DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
public PostRecyclerAdapter(ArrayList<PostModel> postModelArrayList, Context context) {
this.postList = postModelArrayList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// check if post is liked or not
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
// check if current post is liked from this user
if (snapshot.child(holder.id).hasChild(user.getUid())) {
// post is liked form this user
holder.like_btn.setImageResource(R.drawable.ic_thumb_up_filled);
} else {
// post is not liked from this user
holder.like_btn.setImageResource(R.drawable.ic_thump_up_outline);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
// Get current post id set username, authorID, profile picture URL, likes and post image URL
holder.id = postList.get(position).getId();
holder.username.setText(postList.get(position).getName());
holder.userID = postList.get(position).getAuthorID();
holder.like_counter_tv.setText(postList.get(position).getLikes());
Glide.with(context).load(postList.get(position).getImgUrl()).into(holder.postImg);
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
// profilePictureUrl IS ALWAYS NULL
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(holder.profileImage);
}
}
}
#Override
public int getItemCount() {
return postList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
CardView container;
String id;
TextView username, like_counter_tv;
ImageView postImg;
ImageButton like_btn;
CircleImageView profileImage;
boolean isLiked = false;
String userID;
public void updateLikes(String postID, boolean isNotLiked) {
postRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
String currentLikesToString = snapshot.child(postID).child("likes").getValue().toString();
int currentLikesToInt = Integer.parseInt(currentLikesToString);
if (isNotLiked) {
int newCurrentLikes = currentLikesToInt + 1;
String newCurrentLikesToString = Integer.toString(newCurrentLikes);
// Update likes on Real-time DB
postRef.child(postID).child("likes").setValue(newCurrentLikesToString);
// update likes on TextView
like_counter_tv.setText(newCurrentLikesToString);
} else {
int newCurrentLikes = currentLikesToInt - 1;
String newCurrentLikesToString = Integer.toString(newCurrentLikes);
// Update likes on Real-time DB
postRef.child(postID).child("likes").setValue(newCurrentLikesToString);
// update likes on TextView
like_counter_tv.setText(newCurrentLikesToString);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
}
public ViewHolder(#NonNull View itemView) {
super(itemView);
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
final ConstraintLayout sContainer = itemView.findViewById(R.id.second_container);
profileImage = itemView.findViewById(R.id.user_profile_image);
container = itemView.findViewById(R.id.post_item_container);
username = itemView.findViewById(R.id.post_username);
postImg = itemView.findViewById(R.id.post_image);
like_btn = itemView.findViewById(R.id.likeBtn);
like_counter_tv = itemView.findViewById(R.id.like_counter);
likeRef.keepSynced(true);
profileImage.setOnClickListener(v -> {
Intent intent = new Intent(context, UserProfileActivity.class);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
if (snap.child("name").getValue().toString().equals(username.getText().toString())) {
UserProfileActivity.username = username.getText().toString();
UserProfileActivity.userID = snap.child("id").getValue().toString();
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(context, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
context.startActivity(intent);
});
sContainer.setOnLongClickListener(v -> {
FragmentManager manager = ((AppCompatActivity) context).getSupportFragmentManager();
PostOptionsDialog optionsDialog = new PostOptionsDialog();
optionsDialog.setPostId(id);
if (username.getText().toString().equals(user.getDisplayName())) {
optionsDialog.setAuthor(true);
} else {
optionsDialog.setAuthor(false);
}
optionsDialog.show(manager, "options");
return false;
});
like_btn.setOnClickListener(v -> {
// animate like button when clicked
YoYo.with(Techniques.Shake)
.duration(500)
.repeat(0)
.playOn(like_btn);
isLiked = true;
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (isLiked) {
if (snapshot.child(id).hasChild(user.getUid())) {
// post is liked from this user, so user wants to unlike this post
like_btn.setImageResource(R.drawable.ic_thump_up_outline);
likeRef.child(id).child(user.getUid()).removeValue();
isLiked = false;
Toast.makeText(context, "You unliked this meme!", Toast.LENGTH_SHORT).show();
// update likes to DB
updateLikes(id, false);
} else {
// post is not liked from ths user, so the user wants to like this post
like_btn.setImageResource(R.drawable.ic_thumb_up_filled);
likeRef.child(id).child(user.getUid()).setValue("true");
Toast.makeText(context, "You liked this meme!", Toast.LENGTH_SHORT).show();
// update likes to DB
updateLikes(id, true);
}
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(itemView.getContext(), "Error: " + error, Toast.LENGTH_LONG).show();
}
});
});
}
}
}
HomeFragment:
public class HomeFragment extends Fragment {
LoadingDialog progressDialog;
final DatabaseReference postsRef = FirebaseDatabase.getInstance().getReference("posts");
final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
final RecyclerView recyclerView = view.findViewById(R.id.home_recycler_view);
final ArrayList<PostModel> postModelArrayList = new ArrayList<>();
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
final RecyclerView.Adapter recyclerAdapter = new PostRecyclerAdapter(postModelArrayList, getContext());
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
progressDialog = LoadingDialog.Companion.get(getActivity());
progressDialog.show();
postsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
progressDialog.hide();
for (DataSnapshot snap : snapshot.getChildren()) {
PostModel postModel = new PostModel();
postModel.setId(snap.child("id").getValue(String.class));
postModel.setImgUrl(snap.child("imgUrl").getValue(String.class));
postModel.setLikes(snap.child("likes").getValue(String.class));
postModel.setName(snap.child("name").getValue(String.class));
// find user id and set profile picture by name
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot snap1 : snapshot1.getChildren()) {
if (snap1.child("name").getValue(String.class).equals(snap.child("name").getValue(String.class))) {
postModel.setAuthorID(snap1.child("id").getValue(String.class));
postModel.setProfileImgUrl(snap1.child("profileImgUrl").getValue(String.class));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
postModelArrayList.add(postModel);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
I had user shared preferences to get the current Uid or other Uid from realtime database. But I need to do the same without the use of shared preferences. This is for my ProfileActivity and I am using viewpager with three different fragments. The shared preferences show only the current user's profile even when searched for other user in the app.
The image attached is the output of the profile activity in my smartphone. The top bar containing the username and the logout button is of the profile activity and the rest below the blue banner is of the viewpager
public class ProfileActivity extends AppCompatActivity {
private ImageView logout;
private TextView post;
private FloatingActionButton floatingActionButton;
private TabLayout tabLayout;
private ViewPager viewPager;
private TextView username;
private FirebaseUser fUser;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
String profileId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
fUser = FirebaseAuth.getInstance().getCurrentUser();
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Users").child(Objects.requireNonNull(firebaseAuth.getUid()));
String data = getBaseContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
logout = findViewById(R.id.log_out);
username = findViewById(R.id.username);
floatingActionButton = findViewById(R.id.floatingActionButton);
post = findViewById(R.id.posts_account);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
VPAdapter vpAdapter = new VPAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
vpAdapter.addFragment(new Profile(), "Profile");
vpAdapter.addFragment(new MyPosts(), "Posts");
if (profileId.equals(fUser.getUid())){
vpAdapter.addFragment(new SavedPosts(), "Saved");
}
viewPager.setAdapter(vpAdapter);
getPostCount();
userInfo();
getSupportActionBar().hide();
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, PostActivity.class));
finish();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(ProfileActivity.this).create();
alertDialog.setTitle("Are you sure to logout?");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(ProfileActivity.this, StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
finish();
}
});
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
}
});
}
private void getPostCount() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int counter = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts posts = snapshot.getValue(Posts.class);
if (posts.getPublisher().equals(profileId)) counter ++;
}
post.setText(String.valueOf(counter));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
username.setText("#" + user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the profile activity
public class MyPosts extends Fragment {
private RecyclerView recyclerView;
private PostAdapter photoAdapter;
private List<Posts> myPhotoList;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_thoughts, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
recyclerView = view.findViewById(R.id.recycler_view_pictures);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
myPhotoList = new ArrayList<>();
photoAdapter = new PostAdapter(getContext(), myPhotoList);
recyclerView.setAdapter(photoAdapter);
myPhotos();
return view;
}
private void myPhotos() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myPhotoList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts post = snapshot.getValue(Posts.class);
if (post.getPublisher().equals(profileId)){
myPhotoList.add(post);
}
}
Collections.reverse(myPhotoList);
photoAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
the above is the code for the posts fragments inside the viewpager of the profile activity
public class Profile extends Fragment {
private CircleImageView imageProfile;
private TextView followers;
private TextView following;
private TextView fullname;
private TextView bio;
private CircleImageView verification;
private TextView usernamebottom;
private Button editProfile;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE).edit().clear().apply();
}
imageProfile = view.findViewById(R.id.image_profile);
verification = view.findViewById(R.id.verification_profile);
followers = view.findViewById(R.id.followers);
following = view.findViewById(R.id.following);
fullname = view.findViewById(R.id.full_name);
bio = view.findViewById(R.id.bio);
usernamebottom = view.findViewById(R.id.username_btm);
editProfile = view.findViewById(R.id.edit_profile);
getFollowersAndFollowingCount();
userInfo();
if (profileId.equals(fUser.getUid())){
editProfile.setText("Edit profile");
} else {
checkFollowingStatus();
}
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String btnText = editProfile.getText().toString();
if (btnText.equals("Edit profile")){
//Go to edit profile
startActivity(new Intent(getContext(), EditProfileActivity.class));
} else{
if (btnText.equals("follow")){
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).removeValue();
}
}
}
});
return view;
}
private void checkFollowingStatus() {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid()).child("following")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(profileId).exists()) {
editProfile.setText("following");
} else {
editProfile.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getFollowersAndFollowingCount() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Follow").child(profileId);
ref.child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followers.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ref.child("following").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
following.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user.getImageurl().equals("default")){
imageProfile.setImageResource(R.drawable.ic_empty_profile);
} else {
Picasso.get().load(user.getImageurl()).into(imageProfile);
}
usernamebottom.setText("#" + user.getUsername());
fullname.setText(user.getName());
bio.setText(user.getBio());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the user detail fragment also in the view pager of my profile activity
Thats the Fragment containing the recyclerView which leads to activity with Chat
public class FragmentBusinessHome extends Fragment {
/* For to do adapter */
private List<String> namesToDo;
private List<String> uids;
private List<String> servicesNames;
private AdapterToDo adapterToDo;
private RecyclerView toDoRecyclerView;
/* For checking requests adapter */
private List<String> userUids;
private List<String> serviceNames;
private List<String> userNames;
private AdapterPendingRequests adapterPendingRequests;
private RecyclerView pendingRequestsRecyclerView;
private FirebaseAuth mAuth;
public FragmentBusinessHome(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_business_home, container, false);
mAuth = FirebaseAuth.getInstance();
namesToDo = new ArrayList<>();
uids = new ArrayList<>();
servicesNames = new ArrayList<>();
userUids = new ArrayList<>();
serviceNames = new ArrayList<>();
userNames = new ArrayList<>();
toDoRecyclerView = view.findViewById(R.id.toDoRecyclerView);
pendingRequestsRecyclerView = view.findViewById(R.id.requestsToApproveRecyclerView);
LinearLayoutManager layoutManagerActive = new LinearLayoutManager(getActivity());
layoutManagerActive.setStackFromEnd(true);
layoutManagerActive.setReverseLayout(true);
toDoRecyclerView.setLayoutManager(layoutManagerActive);
LinearLayoutManager layoutManagerPendingRequests = new LinearLayoutManager(getActivity());
layoutManagerPendingRequests.setStackFromEnd(true);
layoutManagerPendingRequests.setReverseLayout(true);
pendingRequestsRecyclerView.setLayoutManager(layoutManagerPendingRequests);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference checkRequests = FirebaseDatabase.getInstance().getReference("Providers").child(uid).child("Gigs");
checkRequests.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.getValue(String.class).equals("active")) {
DatabaseReference getRequests = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("pending");
getRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
serviceNames.clear(); userNames.clear(); userUids.clear();
for (DataSnapshot data : dataSnapshot.getChildren()) {
String userName = data.child("names").getValue(String.class);
String serviceName = ds.getKey();
String userUid = data.getKey();
userNames.add(userName);
serviceNames.add(serviceName);
userUids.add(userUid);
adapterPendingRequests = new AdapterPendingRequests(getActivity(), userUids, userNames, serviceNames, mAuth.getCurrentUser().getUid());
adapterPendingRequests.notifyDataSetChanged();
pendingRequestsRecyclerView.setAdapter(adapterPendingRequests);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference getActive = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("active");
getActive.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userUids.clear(); namesToDo.clear(); servicesNames.clear();
for(DataSnapshot datas : dataSnapshot.getChildren()){
String userUid = datas.getKey();
String userName = datas.child("names").getValue(String.class);
String serviceName = ds.getKey();
userUids.add(userUid);
namesToDo.add(userName);
servicesNames.add(serviceName);
Log.d("TAG", userUids.toString());
adapterToDo = new AdapterToDo(getActivity(), namesToDo, userUids, servicesNames);
adapterToDo.notifyDataSetChanged();
toDoRecyclerView.setAdapter(adapterToDo);
if(!userUids.isEmpty()){
LinearLayout toDoLayout = view.findViewById(R.id.toDoLayout);
toDoLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
Thats fragment's activity
private ImageButton moreBtn, chatsBtn;
private BottomNavigationView bottomNavigationView;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_home);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentBusinessHome()).commit();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationListener);
moreBtn = findViewById(R.id.moreBtn);
chatsBtn = findViewById(R.id.chatsBtn);
moreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final PopupMenu popup = new PopupMenu(BusinessHomeActivity.this, moreBtn);
popup.getMenuInflater().inflate(R.menu.popup_toolbar_more_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_btn:
mAuth.signOut();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Intent to_login_activity = new Intent(BusinessHomeActivity.this, WelcomeActivity.class);
startActivity(to_login_activity);
finish();
}
}, 1000);
}
return true;
}
});
}
});
chatsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(BusinessHomeActivity.this, "Will be available soon!", Toast.LENGTH_LONG).show();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.home:
selectedFragment = new FragmentBusinessHome();
break;
case R.id.inbox:
selectedFragment = new FragmentInbox();
break;
case R.id.profile:
selectedFragment = new FragmentProfile();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
That's the adapter for the fragment
public class AdapterToDo extends RecyclerView.Adapter<AdapterToDo.MyHolder> {
Context context;
List<String> namesToDo;
List<String> uids;
List<String> servicesNames;
public AdapterToDo(Context context, List<String> namesToDo, List<String> uids, List<String> servicesNames) {
this.context = context;
this.namesToDo = namesToDo;
this.uids = uids;
this.servicesNames = servicesNames;
}
#NonNull
#Override
public AdapterToDo.MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.to_do_item, parent, false);
return new AdapterToDo.MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final AdapterToDo.MyHolder holder, final int position) {
holder.userNames.setText(namesToDo.get(position));
String currentUid = uids.get(position);
String currentOppositeName = namesToDo.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent to_chat_activity = new Intent(context, ChatActivity.class);
to_chat_activity.putExtra("oppositeUid", currentUid);
to_chat_activity.putExtra("oppositeNames", currentOppositeName);
to_chat_activity.putExtra("class", getClass().getName());
context.startActivity(to_chat_activity);
}
});
}
#Override
public int getItemCount() {
return uids.size();
}
class MyHolder extends RecyclerView.ViewHolder {
private TextView userNames;
private MyHolder(#NonNull View itemView) {
super(itemView);
userNames = itemView.findViewById(R.id.userNames);
}
}
}
That is the Activity where the fragment's adapter leads to
private String oppositeUid, oppositeNames, className;
private TextView oppositeNamesTextView;
private Button sendBtn;
private EditText message;
private FirebaseAuth mAuth;
private RecyclerView recyclerView;
private List<ModelChat> modelChatList;
private AdapterChat chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
Intent intent = getIntent();
oppositeUid = intent.getStringExtra("oppositeUid");
oppositeNames = intent.getStringExtra("oppositeNames");
className = intent.getStringExtra("class");
Log.d("CLASSNAME", className);
modelChatList = new ArrayList<>();
oppositeNamesTextView = findViewById(R.id.oppositeNames);
sendBtn = findViewById(R.id.sendBtn);
message = findViewById(R.id.message);
recyclerView = findViewById(R.id.chatRecyclerView);
LinearLayoutManager linearLayout = new LinearLayoutManager(this);
linearLayout.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayout);
oppositeNamesTextView.setText(oppositeNames);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String mMessage = message.getText().toString().trim();
if(!TextUtils.isEmpty(mMessage)){
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("sender", mAuth.getCurrentUser().getUid());
hashMap.put("receiver", oppositeUid);
hashMap.put("message", mMessage);
hashMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.d("TAG", "PRESSED");
}
The PROBLEM is that when the fragment opens the activity (it contains messages in chat between to users, which are loaded perfectly fine) and the activity detects any change in the chats database reference it stops and loads the previous activity (where the fragment is placed). I wonder what the solution is and I would be glad if you help me.
I'm building a simple chat application. In user fragment, if we click on user it get crashed and go to previous activity if there is previous chat. While there is no chat with that user fragment works fine, but when we type message and click send message store on Firebase and app crashes, similarly if there is chat, chat fragment get crashed.
I think problem is in mReference.addValueEventListener(new ValueEventListener()) method. Code and error is given below. I saw other answers but didn't understand with my code.
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser mFirebaseUser;
DatabaseReference mDatabaseReference;
ImageView btn_send;
EditText send_msg;
Intent mIntent;
MessageAdapter mMessageAdapter;
List<Chat> mChats;
RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
btn_send = findViewById(R.id.img_btn_send);
send_msg = findViewById(R.id.text_send);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mIntent = getIntent();
final String userid = mIntent.getStringExtra("userid");
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = send_msg.getText().toString();
if (!msg.equals("")){
sendMessage(mFirebaseUser.getUid(), userid, msg);
}
send_msg.setText("");
}
});
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
assert user != null;
username.setText(user.getUsername());
if ( user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher_round);
}else {
Glide.with(MessageActivity.this).load(user.getImageURL()).into(profile_image);
}
readMessage(mFirebaseUser.getUid(), userid, user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
mDatabaseReference.child("Chats").setValue(hashMap);
}
private void readMessage(final String myId, final String userID, final String imageURL){
mChats = new ArrayList<>();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Chats");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChats.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Chat chat = dataSnapshot1.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userID) || chat.getReceiver().equals(userID) && chat.getSender().equals(myId)){
mChats.add(chat);
}
mMessageAdapter = new MessageAdapter(MessageActivity.this, mChats, imageURL);
mRecyclerView.setAdapter(mMessageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
ChatsFragment.java
public class ChatsFragment extends Fragment {
private RecyclerView mRecyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
FirebaseUser fUser;
DatabaseReference mReference;
private List<String> userList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chats, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fUser = FirebaseAuth.getInstance().getCurrentUser();
userList = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Chats");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getSender().equals(fUser.getUid())){
userList.add(chat.getReceiver());
}
if (chat.getReceiver().equals(fUser.getUid())){
userList.add(chat.getSender());
}
}
readChats();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
private void readChats() {
mUsers = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Users");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
for (String id : userList){
if (user.getId().equals(id)){
if (mUsers.size() != 0){
for ( User user1 : mUsers){
if ( !user.getId().equals(user1.getId()));
mUsers.add(user);
}
}
else{
mUsers.add(user);
}
}
}
}
mUserAdapter = new UserAdapter(getContext(), mUsers);
mRecyclerView.setAdapter(mUserAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Error is :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.4:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.4:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.4:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.4:212)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6228)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Structure of database
At first , while testing when the user is logged in or fully registered there is no exception or error but when the user signs out and reopen the app the app crashes . the logcat is basically pointing the error on this :
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener()
But if i change the currentUserID to Users .. the app stops crashing and runs smoothly but it doesnot loads up the username and the profile image that is located in the naviagation drawer.
mainactivity.java
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postlist;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private FirebaseUser FirebaseUser;
private DatabaseReference UsersRef;
private CircleImageView NavProfileImage;
private ImageButton AddNewPostButton;
private TextView NavProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
final FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
mToolbar =(Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,drawerLayout,R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
AddNewPostButton = (ImageButton)findViewById(R.id.add_new_post_button);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View navView = navigationView.inflateHeaderView(R.layout.nav_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{ if (dataSnapshot.hasChild("fullname")){
String fullname = dataSnapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}else {
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{ UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToPostActivity();
}
});
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent (MainActivity.this,PostActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
}
private void CheckUserExistance()
{
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
sendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void sendUserToLoginActivity()
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
after signout mFirebaseUser gets null value so this currentUserID value also gets null to avoid nullpointerexception do null check before you use currentUserID like below code
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postlist;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private FirebaseUser FirebaseUser;
private DatabaseReference UsersRef;
private CircleImageView NavProfileImage;
private ImageButton AddNewPostButton;
private TextView NavProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
final FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
mToolbar =(Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,drawerLayout,R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
AddNewPostButton = (ImageButton)findViewById(R.id.add_new_post_button);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View navView = navigationView.inflateHeaderView(R.layout.nav_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
// replace below code
if (mFirebaseUser != null) {
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{ if (dataSnapshot.hasChild("fullname")){
String fullname = dataSnapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}else {
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
sendUserToLoginActivity();
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{ UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToPostActivity();
}
});
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent (MainActivity.this,PostActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
}
private void CheckUserExistance()
{
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
sendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void sendUserToLoginActivity()
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
OR you can check directly here also
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}else{
sendUserToLoginActivity();
}
I think you are getting null in currentUserId and then passing null to firebase. may be you are not getting user id make sure that user is logged in and then check that you are getting user id from firebase or not . if you are getting user id from firebase then try this .
UsersRef.child("Users").child(currentUserID).addValueEventListener(new
ValueEventListener(){ }
and make sure that all keys in your User Model class is public , i worked on firebase for about a month regularly and i faced many issues like this .
If you check I believe you don't have any logged in user that's why you are getting null value in currentUserID.
You are checking if user is logged in or not in OnStart(), you have to check that in onCreate() also. Because in activity lifecycle onCreate() is called before onStart().
Here is how your onCreate function should look:
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
//Your code ...
}
You are getting java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() because when you are signing out the user, you aren't sending him to a login activity and that's why this error. The simplest way to solve this is to use a listener. Let's assume you have two activities, the LoginActivity and the MainActivity. The listener that can be created in the LoginActivity should look like this:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
};
This basically means that if the user is logged in, skip the LoginActivity and go to the MainActivity.
Instantiate the FirebaseAuth object:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
And start listening for changes in your onStart() method like this:
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
In the MainActivity, you should do the same thing:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Which basically means that if the user is not logged in, skip the MainActivity and go to the LoginActivity. In this activity you should do the same thing as in the LoginActivity, you should start listening for changes in the onStart().
In this way, you'll never get an error like that again.