Unusual Intent or Firebase bug in my Android app - java

Hi Stackoverflow community!
I am quite a beginner at Java and Android programming, but I am learning really fast. Recently I have got very strange error. I do not know what is this error about. There is absolutely no code or logcat errors. I think that the whole situation might be about ProfileFragment intent connecting FollowingFragment (which, in a strange turn of events is intentionally extending AppCompatActivity class). I think there can be also a bug with my Firebase usage but I don't really know. But here is an explanation of this error: After the said intent FollowingFragment displays nothing, just white blank space. There should be following users displayed. No crashes occur, no logcat errors also, generally nothing. What is wrong with it? Here is my code:
ProfileFragment:
public class ProfileFragment extends Fragment {
private static final String TAG = "ProfileFragment";
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
OnGridImageSelectedListener mOnGridImageSelectedListener;
private static final int ACTIVITY_NUM = 4;
private static final int NUM_GRID_COLUMNS = 3;
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
//widgets
private TextView mPosts, mFollowers, mFollowing, mDisplayName, mUsername, mWebsite, mDescription;
private ProgressBar mProgressBar;
private CircleImageView mProfilePhoto;
private GridView gridView;
private Toolbar toolbar;
private ImageView profileMenu;
private BottomNavigationViewEx bottomNavigationView;
private Context mContext;
static class ViewHolder{
User user = new User();
}
ViewHolder holder = new ViewHolder();
//vars
private int mFollowersCount = 0;
private int mFollowingCount = 0;
private int mPostsCount = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
mDisplayName = (TextView) view.findViewById(R.id.display_name);
mUsername = (TextView) view.findViewById(R.id.username);
mWebsite = (TextView) view.findViewById(R.id.website);
mDescription = (TextView) view.findViewById(R.id.description);
mProfilePhoto = (CircleImageView) view.findViewById(R.id.profile_photo);
mPosts = (TextView) view.findViewById(R.id.tvPosts);
mFollowers = (TextView) view.findViewById(R.id.tvFollowers);
mFollowing = (TextView) view.findViewById(R.id.tvFollowing);
mProgressBar = (ProgressBar) view.findViewById(R.id.profileProgressBar);
gridView = (GridView) view.findViewById(R.id.gridView);
toolbar = (Toolbar) view.findViewById(R.id.profileToolBar);
profileMenu = (ImageView) view.findViewById(R.id.profileMenu);
bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
mFirebaseMethods = new FirebaseMethods(getActivity());
Log.d(TAG, "onCreateView: stared.");
setupBottomNavigationView();
setupToolbar();
setupFirebaseAuth();
setupGridView();
getFollowersCount();
getFollowingCount();
getPostsCount();
TextView editProfile = (TextView) view.findViewById(R.id.textEditProfile);
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to " + mContext.getString(R.string.edit_profile_fragment));
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.calling_activity), getString(R.string.profile_activity));
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
// TextView mFollowing = (TextView) view.findViewById(R.id.tvFollowing);
mFollowing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getActivity(), FollowingFragment.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
return view;
}
#Override
public void onAttach(Context context) {
try{
mOnGridImageSelectedListener = (OnGridImageSelectedListener) getActivity();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
super.onAttach(context);
}
private void setupGridView(){
Log.d(TAG, "setupGridView: Setting up image grid.");
final ArrayList<Photo> photos = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_photos))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Photo photo = new Photo();
Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();
try {
photo.setCaption(objectMap.get(getString(R.string.field_caption)).toString());
photo.setTags(objectMap.get(getString(R.string.field_tags)).toString());
photo.setPhoto_id(objectMap.get(getString(R.string.field_photo_id)).toString());
photo.setUser_id(objectMap.get(getString(R.string.field_user_id)).toString());
photo.setDate_created(objectMap.get(getString(R.string.field_date_created)).toString());
photo.setImage_path(objectMap.get(getString(R.string.field_image_path)).toString());
ArrayList<Comment> comments = new ArrayList<Comment>();
for (DataSnapshot dSnapshot : singleSnapshot
.child(getString(R.string.field_comments)).getChildren()) {
Comment comment = new Comment();
comment.setUser_id(dSnapshot.getValue(Comment.class).getUser_id());
comment.setComment(dSnapshot.getValue(Comment.class).getComment());
comment.setDate_created(dSnapshot.getValue(Comment.class).getDate_created());
comments.add(comment);
}
photo.setComments(comments);
List<Like> likesList = new ArrayList<Like>();
for (DataSnapshot dSnapshot : singleSnapshot
.child(getString(R.string.field_likes)).getChildren()) {
Like like = new Like();
like.setUser_id(dSnapshot.getValue(Like.class).getUser_id());
likesList.add(like);
}
photo.setLikes(likesList);
photos.add(photo);
}catch(NullPointerException e){
Log.e(TAG, "onDataChange: NullPointerException: " + e.getMessage() );
}
}
//setup our image grid
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
ArrayList<String> imgUrls = new ArrayList<String>();
for(int i = 0; i < photos.size(); i++){
imgUrls.add(photos.get(i).getImage_path());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview,
"", imgUrls);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mOnGridImageSelectedListener.onGridImageSelected(photos.get(position), ACTIVITY_NUM);
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
private void getFollowersCount(){
mFollowersCount = 0;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.dbname_followers))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found follower:" + singleSnapshot.getValue());
mFollowersCount++;
}
mFollowers.setText(String.valueOf(mFollowersCount));
}
#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);
}
} */
private void getFollowingCount(){
mFollowingCount = 0;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.dbname_following))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found following user:" + singleSnapshot.getValue());
mFollowingCount++;
}
mFollowing.setText(String.valueOf(mFollowingCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getPostsCount(){
mPostsCount = 0;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.dbname_user_photos))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found post:" + singleSnapshot.getValue());
mPostsCount++;
}
mPosts.setText(String.valueOf(mPostsCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setProfileWidgets(UserSettings userSettings) {
//Log.d(TAG, "setProfileWidgets: setting widgets with data retrieving from firebase database: " + userSettings.toString());
//Log.d(TAG, "setProfileWidgets: setting widgets with data retrieving from firebase database: " + userSettings.getSettings().getUsername());
//User user = userSettings.getUser();
UserAccountSettings settings = userSettings.getSettings();
UniversalImageLoader.setImage(settings.getProfile_photo(), mProfilePhoto, null, "");
mDisplayName.setText(settings.getDisplay_name());
mUsername.setText(settings.getUsername());
mWebsite.setText(settings.getWebsite());
mDescription.setText(settings.getDescription());
mProgressBar.setVisibility(View.GONE);
}
/**
* Responsible for setting up the profile toolbar
*/
private void setupToolbar(){
((ProfileActivity)getActivity()).setSupportActionBar(toolbar);
profileMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to account settings.");
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
BottomNavigationViewHelper.enableNavigation(mContext,getActivity() ,bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//retrieve user information from the database
setProfileWidgets(mFirebaseMethods.getUserSettings(dataSnapshot));
//retrieve images for the user in question
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
FollowingFragment.java
public class FollowingFragment extends AppCompatActivity{
private ArrayList<Photo> mPhotos;
private ArrayList<Photo> mPaginatedPhotos;
private ArrayList<String> mFollowing;
private ListView mListView;
private MainfeedListAdapter mAdapter;
private int mResults;
TextView username;
CircleImageView profilePhoto;
#Nullable
public View onCreateView(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_following);
mListView = (ListView) findViewById(R.id.listView1);
mFollowing = new ArrayList<>();
mPhotos = new ArrayList<>();
getIncomingIntent();
getFollowing();
return mListView;
}
private void getItDone(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_followrow, container, false);
username = (TextView) view.findViewById(R.id.following_username2);
profilePhoto = (CircleImageView) view.findViewById(R.id.following_profile_image2);}
private void getIncomingIntent(){
Intent intent = getIntent();
}
private void getFollowing(){
Log.d(TAG, "getFollowing: searching for following");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_following))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.child(getString(R.string.field_user_id)).getValue());
mFollowing.add(singleSnapshot.child(getString(R.string.field_user_id)).getValue().toString());
mFollowing.add(FirebaseAuth.getInstance().getCurrentUser().getUid());
username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(
singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
profilePhoto);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

Add a Toast to check that the values are retrieving or not as -
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Toast.makeText(this, ""+ dataSnapshot, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.child(getString(R.string.field_user_id)).getValue());
mFollowing.add(singleSnapshot.child(getString(R.string.field_user_id)).getValue().toString());
mFollowing.add(FirebaseAuth.getInstance().getCurrentUser().getUid());
username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(
singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
profilePhoto);
}

Related

When I click on different person Chat room the app opening the same person chat

I'm facing a problem please check find the problem: When I click on a different chat room it opening the same chat room as you can see below:
Here is the Chatsfragment.java (Left side screen)
public class ChatsFragment extends Fragment{
private RecyclerView recyclerView;
private FriendsAdapter userAdapter;
private List<Users> mUsers;
FirebaseUser fuser;
DatabaseReference reference;
private List<String> usersList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_chats, container, false);
recyclerView = view.findViewById(R.id.ChatsFragment_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
usersList = new ArrayList<>();
fuser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Chat chat=snapshot.getValue(Chat.class);
assert chat != null;
if (chat.getSender().equals(fuser.getUid())) {
usersList.add(chat.getReceiver());
}
if (chat.getReceiver().equals(fuser.getUid())) {
usersList.add(chat.getSender());
}
}
Set<String> hashSet = new HashSet<String>(usersList);
usersList.clear();
usersList.addAll(hashSet);
readChats();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
UpdateToken();
return view;
}
private void UpdateToken() {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String refreshToken = FirebaseInstanceId.getInstance().getToken();
Token token = new Token(refreshToken);
FirebaseDatabase.getInstance().getReference("Tokens").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(token);
}
private void readChats() {
mUsers=new ArrayList<>();
reference= FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//mUsers.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Users user=snapshot.getValue(Users.class);
for(String id:usersList)
{
assert user != null;
if (user.getUser_id().equals(id)) {
mUsers.add(user);
}
}
}
userAdapter=new FriendsAdapter(getContext(),mUsers,true);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
Here is the MessageActivity.java(Right side screen)
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username,fullname;
FirebaseUser fuser;
DatabaseReference reference;
private Toolbar toolbar;
Intent intent;
boolean notify = false;
TextView btn_send;
EditText text_send;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
String userid;
private APIService apiService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
toolbar = findViewById(R.id.MessageActivity_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = (TextView)findViewById(R.id.MessageActivity_userName);
fullname = (TextView)findViewById(R.id.MessageActivity_fullname);
profile_image = (CircleImageView)findViewById(R.id.MessageActivity_user_img);
btn_send =findViewById(R.id.MessageActivity_btn_send);
text_send = findViewById(R.id.MessageActivity_text_send);
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
recyclerView = findViewById(R.id.MessageActivity_recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
intent = getIntent();
userid = intent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
username.setText(user.getUsername());
fullname.setText(user.getFullName());
Glide.with(MessageActivity.this)
.load(user.getProfilePhoto())
.into(profile_image);
readMesagges(fuser.getUid(), userid, user.getProfilePhoto());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notify = true;
String msg = text_send.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(), userid, msg);
} else {
Toast.makeText(MessageActivity.this, "You can't send empty message", Toast.LENGTH_SHORT).show();
}
text_send.setText("");
closeKeyboard();
}
});
}
private void sendMessage(String sender, final String receiver, String message){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
hashMap.put("isseen", false);
reference.child("Chats").push().setValue(hashMap);
final String msg = message;
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
if (notify) {
sendNotifiaction(receiver, user.getUsername(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendNotifiaction(String receiver, final String username, final String message) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(receiver);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.ic_launcher, username+":"+message, "New Message",
userid);
NotificationSender sender = new NotificationSender(data, token.getToken());
apiService.sendNotification(sender).enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.code() == 200){
if (response.body().success != 1){
Toast.makeText(MessageActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readMesagges(final String myid, final String userid, final String imageurl){
mchat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mchat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myid)){
mchat.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, mchat, imageurl);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void closeKeyboard(){
View view = this.getCurrentFocus();
if(view != null){
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} }
Here is the FriendsAdapter.java
public FriendsAdapter(Context mcontext, List<Users> muser, boolean ischat) {
this.mcontext = mcontext;
this.muser = muser;
this.ischat = ischat;
}
#NonNull
#Override
public FriendsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mcontext).inflate(R.layout.friends_single_layout,parent,false);
return new FriendsAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsAdapter.ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
users = muser.get(position);
holder.username.setText(users.getFullName());
// holder.fullname.setText(users.getFullName());
Glide.with(mcontext)
.load(users.getProfilePhoto())
.into(holder.profileimage);
if (ischat){
lastMessage(users.getUser_id(), holder.last_msg);
} else {
holder.last_msg.setText(users.getFullName());
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, MessageActivity.class);
intent.putExtra("userid",users.getUser_id());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return muser.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username,last_msg;
public CircleImageView profileimage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.FriendSingle_userName);
last_msg = itemView.findViewById(R.id.FriendSingle_lastMsg);
profileimage = itemView.findViewById(R.id.FriendSingle_user_img);
}
}
//check for last message
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText(users.getFullName());
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
Again, the problem is whenever user click on recyclerView item it shows the same chat room, please find the errer and let me know as soon as possible.
Thanks for your time
From what you've posted (there seems to be part of FriendsAdapter.java missing), it looks like the issue is in your FriendsAdapter. You have probably defined the users variable at the Adapter level, but it should be defined at the ViewHolder level or just used as a local variable.
Your are calling users = muser.get(position) in your bindViewHolder method so if users is defined at adapter level when your onClickListener is fired the users variable will be set to the user of the last cell, instead of the user object associated with the cell clicked.
So, remove the definition of users from adapter level (probably looks like this):
User users;
And either use users as a local variable inside the bindViewHolder method:
User users = muser.get(position);
Or put the definition inside your ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder {
public User users;
public TextView username,last_msg;
public CircleImageView profileimage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.FriendSingle_userName);
last_msg = itemView.findViewById(R.id.FriendSingle_lastMsg);
profileimage = itemView.findViewById(R.id.FriendSingle_user_img);
}
}

How to remove values from Firebase when item is selected in recyclerview?

My app is displaying user's classes in a recylerview. When a user selects a specific class, it opens up another activity that displays the details and there is a button where a user can remove the class. When that button is clicked, i want the id of the class that is saved under the user's list of classes to be removed. I also want the user's uid to be removed from the list of students under the class.Also, I accidentally saved my class id as variable name uid, which shouldn't be confused with the user's uid.Let me know if you have any questions!
Here is my database structure:
{
"Classes" : {
"-LiGRe3e1YF_HFrHKMgi" : {
"Students" : {
"-LiId4URjJ8SWLAP4f4i" : "UhTQgJ4jugMqFtEZK8CsIkTqQl22",
"-LiIeT5t1T7JpcUee_MJ" : "UhTQgJ4jugMqFtEZK8CsIkTqQl22"
},
"class_info" : {
"date_clasname" : "mm",
"room_number" : "jjhh",
"subject" : "Science",
"teacher" : "mm",
"uid" : "-LiGRe3e1YF_HFrHKMgi"
}
}
},
"Users" : {
"UhTQgJ4jugMqFtEZK8CsIkTqQl22" : {
"Classes" : {
"-LiIeT5slTjC0B3lEqNJ" : "-LiGRe3e1YF_HFrHKMgi"
"-LiIeT5slTjC0B3lEqNJ" : "-LiGRe3e1YF_HFrHKMgi"
},
"User_info" : {
"email" : "samuelford48#gmail.com",
"grade" : "12",
"name" : "Samuel"
}
}
}
}
Here is the code of my activity that shows the classes and gets the data from Firebase:
public class home_fragment extends Fragment implements View.OnClickListener {
private Button button;
//DatabaseReference dref;
//ListView listview2;
//ArrayList<String> list=new ArrayList<>();
private FirebaseDatabase database;
private DatabaseReference myRef;
private List<Listdata> list;
private RecyclerView recyclerview;
public home_fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
//FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
//if(fbUser == null) { Intent intent = new Intent(getContext(), LoginActivity.class);
// startActivity(intent);}
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(this);
recyclerview = (RecyclerView) view.findViewById(R.id.rview);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
list = new ArrayList<>();
final adapter_user_remove_class recycler = new adapter_user_remove_class(list);
// final RecyclerviewAdapter2 recycler = new RecyclerviewAdapter2(list);
//String postkey2 = dataSnapshot.getKey();
String class_id = dataSnapshot.getValue(String.class);
myRef = database.getReference("Classes").child(class_id).child("class_info");
// StringBuffer stringbuffer = new StringBuffer();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
Class_model new_class = dataSnapshot.getValue(Class_model.class);
assert new_class != null;
String nameofclass = new_class.getDate_clasname();
String teacherofclass = new_class.getTeacher();
String roomnumberofclass = new_class.getRoom_number();
String class_key = new_class.getUid();
Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass, class_key);
//String name = userdetails.getName();
//String email = userdetails.getEmail();
//String address = userdetails.getAddress();
listdata.setDate_class(nameofclass);
listdata.setTeacher(teacherofclass);
listdata.setRnumber(roomnumberofclass);
// recycler.notifyDataSetChanged();
list.add(listdata);
recycler.notifyDataSetChanged();
//recycler.notifyDataSetChanged();// Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev#vigoschools.org!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
recyclerview.setLayoutManager(layoutmanager);
recyclerview.setItemAnimator(new DefaultItemAnimator());
recyclerview.setAdapter(recycler);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev#vigoschools.org!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
return view;
}
Here is the code for my recycler adapter:
public class adapter_user_remove_class extends RecyclerView.Adapter<adapter_user_remove_class.MyHolder>{
List<Listdata> listdata;
public adapter_user_remove_class(List<Listdata> listdata) {
this.listdata = listdata;
}
#Override
public adapter_user_remove_class.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_model,parent,false);
adapter_user_remove_class.MyHolder myHolder = new adapter_user_remove_class.MyHolder(view);
return myHolder;
}
public void onBindViewHolder(adapter_user_remove_class.MyHolder holder, final int position) {
final Listdata data = listdata.get(position);
holder.vdate_class.setText(data.getDate_class());
holder.vteacher.setText(data.getTeacher());
holder.vrnumber.setText(data.getRnumber());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( final View view) {
Context context = view.getContext();
Intent intent = new Intent(context, user_remove_class.class);
intent.putExtra("date_class", listdata.get(position).getDate_class());
intent.putExtra("teacher", listdata.get(position).getTeacher());
intent.putExtra("room_number", listdata.get(position).getRnumber());
intent.putExtra("post_key", listdata.get(position).getUid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listdata.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView vdate_class , vteacher,vrnumber;
public MyHolder(View itemView) {
super(itemView);
vdate_class = (TextView) itemView.findViewById(R.id.date_class_name);
vteacher = (TextView) itemView.findViewById(R.id.teacher);
vrnumber = (TextView) itemView.findViewById(R.id.room_number);
}
}
}
Here is the code for the activity that shows the details and handles the removal of data from Firebase:
public class user_remove_class extends AppCompatActivity {
private Button remove_class;
private FirebaseDatabase database;
private DatabaseReference myRef, myRef2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_remove_class);
final String date_class2 = getIntent().getStringExtra("date_class");
final String teacher = getIntent().getStringExtra("teacher");
final String room_number = getIntent().getStringExtra("room_number");
final String post_key = getIntent().getStringExtra("post_key");
TextView display_class_name = (TextView) findViewById(R.id.date_tv);
display_class_name.setText(date_class2);
TextView display_teacher = (TextView) findViewById(R.id.teacher_tv);
display_teacher.setText(teacher);
TextView display_room_number = (TextView) findViewById(R.id.rn_tv);
display_room_number.setText(room_number);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
remove_class = (Button) findViewById(R.id.add_class_2);
// final Query query = myRef.orderByChild("classes").equalTo(post_key);
//System.out.println(query);
remove_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
}
});
}
}
You can remove it by :
remove_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes").child(post_key);
myRef.removeValue();
}
});
You can Retrieve the Random key by this method .
MyRef.orderByChild("email").equalTo("blabla#blabla.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User ref", child.getRef().toString());
Log.d("User val", child.getValue().toString());
}
}
Note that you have to pass the email by putExtra method and then match it with equalTo(); method . If email is exits in the random key it will retrive the ramdom key simple . :)
Hope it will work. If it works don't forget to Accept the question.

Error while passing data from clicked item in listview to another activity

After populating the Listview with the list of diaries, upon clicking a particular diary, the corresponding pictures have to be displayed in another activity.
For this, I'm passing the position of clicked item in the intent. But, the app crashes upon execution
This is the history fragment code
public class HistoryFragment extends Fragment
{
ListView lv;
Context context;
public HistoryFragment()
{
//default constructor
}
//The following method will get the context from the activity to which the fragment is attached
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.scrolllist, container, false);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("image").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//List<String> cities = new ArrayList<>();
//cities = new ArrayList<>();
final ArrayList<Word> cities = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String cityName = ds.getKey();
cities.add(new Word(cityName));
}
lv = (ListView)view.findViewById(R.id.list_of_ds);
ContentAdapter arrayAdapter = new ContentAdapter(context,cities);
lv.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
//Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//String diary_name=title.get(position).toString();
Intent myIntent = new Intent(view.getContext(), DiaryViewActivity.class);
myIntent.putExtra("diaryname", lv.getItemAtPosition(position).toString());
startActivity(myIntent);
}
});
return view;
}
}
This is the activity to which intent is passed
//DiaryViewActivity.java
public class DiaryViewActivity extends AppCompatActivity implements IFirebaseLoadDone
{
ViewPager viewPager;
MAdapter adapter;
DatabaseReference diaries;
IFirebaseLoadDone iFirebaseLoadDone;
FirebaseAuth mAuth=FirebaseAuth.getInstance();
//final ArrayList<Word> word = new ArrayList<Word>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diary_view);
Bundle bd = getIntent().getExtras();
String myVal = bd.getString("diaryname");
String currentUser;
currentUser = mAuth.getCurrentUser().getUid();
diaries = FirebaseDatabase.getInstance().getReference().child("image").child(currentUser)
.child(myVal);
iFirebaseLoadDone = this;
loadDairy();
viewPager = (ViewPager)findViewById(R.id.view_pager);
viewPager.setPageTransformer(true,new DepthPageTransformer());
}
private void loadDairy() {
diaries.addListenerForSingleValueEvent(new ValueEventListener() {
List<Display> diaryList = new ArrayList<>();
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data:dataSnapshot.getChildren()) {
Display d = data.getValue(Display.class);
//word.add(new Word(d.dname));
diaryList.add(d);
}
iFirebaseLoadDone.onFirebaseLoadSuccess(diaryList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
iFirebaseLoadDone.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<Display> diaryList) {
adapter = new MAdapter(this,diaryList);
viewPager.setAdapter(adapter);
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this,"error! "+message,Toast.LENGTH_SHORT).show();
}
}
The following error occurs -
Attempt to invoke virtual method 'void android.widget.listview.setonitemclicklistener(android.widget.adapterview$onitemclicklistener)' on a null object reference
At the time that you call lv#setOnItemClickListener, your ListView (lv) hasn't been instantiated yet and won't be until the callback to ValueEventListener#onDataChange happens.

Retrieve users followers list

I am trying to retrieve users followers from Firebase and populate them onto a RecyclerView for anyone to be able to see just like twitter and Instagram, when i run the app it returns an error.
My code:
public class ViewFollowersFragment extends Fragment {
private static final String TAG = "ViewFollowersFragment";
private CircleImageView myprofileimage;
private TextView username;
private ImageView arrow;
private ListView vfollowerslistview;
private DatabaseReference viewFollowersref,viewUserRef;
private FirebaseAuth mAuth;
private FirebaseListAdapter viewfollowersadapter;
private List<User> mUserList;
private User mUser;
String userid;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_followers, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
vfollowerslistview = (ListView) view.findViewById(R.id.viewfollowerslistview);
arrow = (ImageView) view.findViewById(R.id.fragfollowersbackarrow);
arrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
getActivity().finish();
}
});
mUserList = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
userid = mAuth.getUid();
viewFollowersref = FirebaseDatabase.getInstance().getReference().child("User_Account_Settings");
viewUserRef = FirebaseDatabase.getInstance().getReference();
setFollowers();
return view;
}
private void setFollowers () {
Query query = FirebaseDatabase.getInstance().getReference()
.child("Followers")
.child(mUser.getUser_id());
FirebaseListOptions<UserAccountSettings> options = new FirebaseListOptions.Builder<UserAccountSettings>()
.setLayout(R.layout.layout_user_listitem)
.setLifecycleOwner(getActivity())
.setQuery(query,UserAccountSettings.class)
.build();
viewfollowersadapter = new FirebaseListAdapter(options) {
#Override
protected void populateView(View v, Object model, final int position) {
String newfol = getRef(position).getKey();
final TextView username = v.findViewById(R.id.username);
final CircleImageView profile_image = v.findViewById(R.id.profile_image);
viewFollowersref.child(newfol).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("username")) {
String myusername = dataSnapshot.child("username").getValue().toString();
username.setText(myusername);
}
if (dataSnapshot.hasChild("profileimage")) {
String myimage = dataSnapshot.child("profileimage").getValue().toString();
if (myimage.isEmpty()) {
profile_image.setImageResource(R.drawable.pro_pic);
} else {
Picasso.with(getActivity()).load(myimage).placeholder(R.drawable.pro_pic).into(profile_image);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("calling_activity", "Search_Activity");
profileIntent.putExtra("intent_user", mUserList.get(position));
startActivity(profileIntent);
}
});
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("calling_activity", "Search_Activity");
profileIntent.putExtra("intent_user", mUserList.get(position));
startActivity(profileIntent);
}
});
Query userQuery = viewUserRef
.child("Users")
.orderByChild("user_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());
mUserList.add(singleSnapshot.getValue(User.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
vfollowerslistview.setAdapter(viewfollowersadapter);
}
}
I cant seem to fit the entirw code in.
According to your comment, you are getting the following error:
Caused by: java.langCaused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.hope.myapplication.Models.User.getUser_id()' on a null object reference
Because your mUser object on which you are calling getUser_id() method has the value of null. This is happening because you haven't initialized the User object in your code at all. To solve this, please change the following line of code:
Query query = FirebaseDatabase.getInstance().getReference()
.child("Followers")
.child(mUser.getUser_id());
to
Query query = FirebaseDatabase.getInstance().getReference()
.child("Followers")
.child(mAuth.getCurrentUser().getUid());
In which mAuth.getCurrentUser() return a FirebaseUser object, so you can get the correct uid.

Very strange Unreachable statement [duplicate]

This question already has answers here:
I get the error "Unreachable statement" return in android
(3 answers)
Closed 4 years ago.
Hi Stackoverflow community,
At first I would like to say that I am beginner. Recently I noticed really strange error in my code. I just wrote a simple intent from one activity to another and something really strange happened.
Intent part (intent to FollowingActivity) is showing constant error
"Unreachable statement".
Whether or not I apply TextView mFollowing = (TextView) view.findViewById(R.id.tvFollowing); it is showing still that error. What should I do in my case? The most ununderstanable thing is that the previous intent to that (AccountSettingActivity intent) is working really well. Here is my code:
public class ProfileFragment extends Fragment {
private static final String TAG = "ProfileFragment";
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
OnGridImageSelectedListener mOnGridImageSelectedListener;
private static final int ACTIVITY_NUM = 4;
private static final int NUM_GRID_COLUMNS = 3;
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
//widgets
private TextView mPosts, mFollowers, mFollowing, mDisplayName, mUsername, mWebsite, mDescription;
private ProgressBar mProgressBar;
private CircleImageView mProfilePhoto;
private GridView gridView;
private Toolbar toolbar;
private ImageView profileMenu;
private BottomNavigationViewEx bottomNavigationView;
private Context mContext;
static class ViewHolder{
User user = new User();
}
ViewHolder holder = new ViewHolder();
//vars
private int mFollowersCount = 0;
private int mFollowingCount = 0;
private int mPostsCount = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
mDisplayName = (TextView) view.findViewById(R.id.display_name);
mUsername = (TextView) view.findViewById(R.id.username);
mWebsite = (TextView) view.findViewById(R.id.website);
mDescription = (TextView) view.findViewById(R.id.description);
mProfilePhoto = (CircleImageView) view.findViewById(R.id.profile_photo);
mPosts = (TextView) view.findViewById(R.id.tvPosts);
mFollowers = (TextView) view.findViewById(R.id.tvFollowers);
mFollowing = (TextView) view.findViewById(R.id.tvFollowing);
mProgressBar = (ProgressBar) view.findViewById(R.id.profileProgressBar);
gridView = (GridView) view.findViewById(R.id.gridView);
toolbar = (Toolbar) view.findViewById(R.id.profileToolBar);
profileMenu = (ImageView) view.findViewById(R.id.profileMenu);
bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
mFirebaseMethods = new FirebaseMethods(getActivity());
Log.d(TAG, "onCreateView: stared.");
setupBottomNavigationView();
setupToolbar();
setupFirebaseAuth();
setupGridView();
getFollowersCount();
getFollowingCount();
getPostsCount();
TextView editProfile = (TextView) view.findViewById(R.id.textEditProfile);
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to " + mContext.getString(R.string.edit_profile_fragment));
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.calling_activity), getString(R.string.profile_activity));
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
return view;
// TextView mFollowing = (TextView) view.findViewById(R.id.tvFollowing);
mFollowing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to " + mContext.getString(R.string.edit_profile_fragment));
Intent intent = new Intent(getActivity(), FollowingActivity.class);
intent.putExtra(getString(R.string.calling_activity), getString(R.string.profile_activity));
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
#Override
public void onAttach(Context context) {
try{
mOnGridImageSelectedListener = (OnGridImageSelectedListener) getActivity();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
super.onAttach(context);
}
private void setupGridView(){
Log.d(TAG, "setupGridView: Setting up image grid.");
final ArrayList<Photo> photos = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_photos))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Photo photo = new Photo();
Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();
try {
photo.setCaption(objectMap.get(getString(R.string.field_caption)).toString());
photo.setTags(objectMap.get(getString(R.string.field_tags)).toString());
photo.setPhoto_id(objectMap.get(getString(R.string.field_photo_id)).toString());
photo.setUser_id(objectMap.get(getString(R.string.field_user_id)).toString());
photo.setDate_created(objectMap.get(getString(R.string.field_date_created)).toString());
photo.setImage_path(objectMap.get(getString(R.string.field_image_path)).toString());
ArrayList<Comment> comments = new ArrayList<Comment>();
for (DataSnapshot dSnapshot : singleSnapshot
.child(getString(R.string.field_comments)).getChildren()) {
Comment comment = new Comment();
comment.setUser_id(dSnapshot.getValue(Comment.class).getUser_id());
comment.setComment(dSnapshot.getValue(Comment.class).getComment());
comment.setDate_created(dSnapshot.getValue(Comment.class).getDate_created());
comments.add(comment);
}
photo.setComments(comments);
List<Like> likesList = new ArrayList<Like>();
for (DataSnapshot dSnapshot : singleSnapshot
.child(getString(R.string.field_likes)).getChildren()) {
Like like = new Like();
like.setUser_id(dSnapshot.getValue(Like.class).getUser_id());
likesList.add(like);
}
photo.setLikes(likesList);
photos.add(photo);
}catch(NullPointerException e){
Log.e(TAG, "onDataChange: NullPointerException: " + e.getMessage() );
}
}
//setup our image grid
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
ArrayList<String> imgUrls = new ArrayList<String>();
for(int i = 0; i < photos.size(); i++){
imgUrls.add(photos.get(i).getImage_path());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview,
"", imgUrls);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mOnGridImageSelectedListener.onGridImageSelected(photos.get(position), ACTIVITY_NUM);
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
private void getFollowersCount(){
mFollowersCount = 0;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.dbname_followers))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found follower:" + singleSnapshot.getValue());
mFollowersCount++;
}
mFollowers.setText(String.valueOf(mFollowersCount));
}
#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);
}
} */
private void getFollowingCount(){
mFollowingCount = 0;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.dbname_following))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found following user:" + singleSnapshot.getValue());
mFollowingCount++;
}
mFollowing.setText(String.valueOf(mFollowingCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getPostsCount(){
mPostsCount = 0;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.dbname_user_photos))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found post:" + singleSnapshot.getValue());
mPostsCount++;
}
mPosts.setText(String.valueOf(mPostsCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setProfileWidgets(UserSettings userSettings) {
//Log.d(TAG, "setProfileWidgets: setting widgets with data retrieving from firebase database: " + userSettings.toString());
//Log.d(TAG, "setProfileWidgets: setting widgets with data retrieving from firebase database: " + userSettings.getSettings().getUsername());
//User user = userSettings.getUser();
UserAccountSettings settings = userSettings.getSettings();
UniversalImageLoader.setImage(settings.getProfile_photo(), mProfilePhoto, null, "");
mDisplayName.setText(settings.getDisplay_name());
mUsername.setText(settings.getUsername());
mWebsite.setText(settings.getWebsite());
mDescription.setText(settings.getDescription());
mProgressBar.setVisibility(View.GONE);
}
/**
* Responsible for setting up the profile toolbar
*/
private void setupToolbar(){
((ProfileActivity)getActivity()).setSupportActionBar(toolbar);
profileMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to account settings.");
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
BottomNavigationViewHelper.enableNavigation(mContext,getActivity() ,bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//retrieve user information from the database
setProfileWidgets(mFirebaseMethods.getUserSettings(dataSnapshot));
//retrieve images for the user in question
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
Its because of return view; statement move it after mFollowing.setOnClickListener as follows:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
// TextView mFollowing = (TextView) view.findViewById(R.id.tvFollowing);
mFollowing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to " + mContext.getString(R.string.edit_profile_fragment));
Intent intent = new Intent(getActivity(), FollowingActivity.class);
intent.putExtra(getString(R.string.calling_activity), getString(R.string.profile_activity));
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
return view;
}

Categories

Resources