Showing specific button to current user in Android - android

My app has a post layout which have an edit button and the send button. All i want to do is to show only edit button if current user is viewing his/her post and not the send button. Just like a stackoverflow post, you can't edit other's post and can't send a message to yourself. I have tried boolean methods but still no solution. Thanks.
Activity that have showButtonsForCurrentUser() method ;
public class ViewPostActivity extends AppCompatActivity {
private static final String TAG = "ViewPostActivity";
//widgets
private TextView mTitle, mDescription, mPrice, mLocation;
//vars
private String mPostId;
private String userId;
private Post mPost;
private PostImages mPostImages;
private ViewPager viewPager;
private ImageView editPostIcon;
private WormDotsIndicator wormDotsIndicator;
public ViewAdapter viewAdapter;
public DatabaseReference reference;
public FirebaseUser currentUser;
public ArrayList<String> IMAGES = new ArrayList<>();
public ArrayList<Uri> mImageUris = new ArrayList<>();
private SquareImageView postImageView;
private User user;
//Dialog and Sheet vars
private Dialog deleteDialog;
private Button deleteBtnDialog;
private Button deleteBtnSheet;
private Button updateBtn;
private Button sendBtn;
private TextView titleTv, messageTv;
private ImageView closeIcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_post);
mPostId = getIntent().getStringExtra(getString(R.string.arg_post_id));
mTitle = (TextView) findViewById(R.id.post_title);
mDescription = (TextView) findViewById(R.id.post_description);
mPrice = (TextView) findViewById(R.id.post_price);
mLocation = (TextView) findViewById(R.id.post_location);
postImageView = findViewById(R.id.post_image);
sendBtn = findViewById(R.id.send_msg);
viewPager = findViewById(R.id.view_pager_images);
editPostIcon = findViewById(R.id.edit_post_btn);
wormDotsIndicator = findViewById(R.id.dotsindicator);
editPostIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBottomSheetDialog();
}
});
getPostInfo();
showButtonsForCurrentUser();
////MyPosts Layout/////
deleteBtnDialog = findViewById(R.id.dialog_btn);
deleteDialog = new Dialog(this);
////MyPosts Layout/////
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ViewPostActivity.this, MessageActivity.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
});
}
public void showButtonsForCurrentUser(){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
//sendBtn and editPostIcon are set to GONE.
if (currentUser.equals(userId)){
sendBtn.setVisibility(View.VISIBLE);
}else{
editPostIcon.setVisibility(View.VISIBLE);
}
}
private void getPostInfo(){
Log.d(TAG, "getPostInfo: getting the post information.");
reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.node_posts))
.orderByKey()
.equalTo(mPostId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
if(singleSnapshot != null){
mPost = singleSnapshot.getValue(Post.class);
Log.d(TAG, "onDataChange: found the post: " + mPost.getTitle());
mTitle.setText(mPost.getTitle());
mDescription.setText(mPost.getDescription());
String price = "FREE";
if(mPost.getPrice() != null){
price = "$" + mPost.getPrice();
}
mPrice.setText(price);
String location = mPost.getCity();
mLocation.setText(location);
userId = mPost.getUser_id();
if (mPost.getImage() != null){
wormDotsIndicator.setVisibility(View.INVISIBLE);
postImageView.setVisibility(View.VISIBLE);
Picasso.get().load(mPost.getImage()).into(postImageView);
}else {
IMAGES = mPost.getPostImages();
for (int i = 0; i <IMAGES.size(); i++){
Uri myUri = Uri.parse(IMAGES.get(i));
mImageUris.add(myUri);
}
viewAdapter = new ViewAdapter(getApplication(), IMAGES);
viewPager.setAdapter(viewAdapter);
wormDotsIndicator.setViewPager(viewPager);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showBottomSheetDialog() {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ViewPostActivity.this, R.style.BottomSheetDialogTheme);
LinearLayout linearLayout = findViewById(R.id.bottom_sheet_update_container);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottom_sheet_update, linearLayout);
updateBtn = bottomSheetView.findViewById(R.id.update_btnn);
deleteBtnSheet = bottomSheetView.findViewById(R.id.delete_btnn);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent updateActivityIntent = new Intent(ViewPostActivity.this, UpdateActivity.class);
if (IMAGES != null){
updateActivityIntent.putStringArrayListExtra("IMAGES", IMAGES);
updateActivityIntent.putParcelableArrayListExtra("IMAGEURIS", mImageUris);
}else {
String singlePhotoUrl = mPost.getImage();
updateActivityIntent.putExtra("Single Photo url", singlePhotoUrl);
}
updateActivityIntent.putExtra("Başlık", mTitle.getText());
updateActivityIntent.putExtra("Açıklama", mDescription.getText());
updateActivityIntent.putExtra("Fiyat", mPrice.getText());
updateActivityIntent.putExtra("mPostId", mPostId);
startActivity(updateActivityIntent);
bottomSheetDialog.dismiss();
}
});
deleteBtnSheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDeleteDialog();
}
});
}
public void showDeleteDialog(){
deleteDialog.setContentView(R.layout.positive_dialog);
closeIcon = deleteDialog.findViewById(R.id.close_dialog);
deleteBtnDialog = deleteDialog.findViewById(R.id.dialog_btn);
titleTv = deleteDialog.findViewById(R.id.titleTv);
messageTv = deleteDialog.findViewById(R.id.message_dialog);
closeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteDialog.dismiss();
}
});
deleteDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
deleteDialog.show();
deleteBtnDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletePost(mPostId);
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);
deleteDialog.dismiss();
}
});
}
private void deletePost(String deletePostId){
Bundle args = new Bundle();
args.putString(getString(R.string.arg_post_id), deletePostId);
Query deleteQuery = reference.child("posts").orderByChild("post_id").equalTo(deletePostId);
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot delData: dataSnapshot.getChildren()){
delData.getRef().removeValue();
Intent backIntent = new Intent(ViewPostActivity.this, SearchActivity.class);
startActivity(backIntent);
}
Toast.makeText(ViewPostActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewPostActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void status(String status){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
status("offline");
}
}

what are the values for mPostId?
I would log the userID and currentuser values thats being retrieved, to check if there is no issue your query. The boolean part should work

Related

Can not delete item that is selected, only deletes the last item added

I'm trying to delete the selected item in my RecyclerView, but when I click on my delete Button it just deletes the last item added. And after I delete the last item added I can not delete anymore. What am I missing?
MainActivity
public class MainWishActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView wishList;
private androidx.appcompat.widget.Toolbar mToolbar;
private ImageButton ibaddnewwishlist;
private CircleImageView NavProfileImage;
private TextView NavProfileFirstName, NavProfileLastName;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, WishListRef;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wish);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(" Dine Ønskelister");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainWishActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
ibaddnewwishlist = (ImageButton)findViewById(R.id.ib_addnewwishlist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
wishList = (RecyclerView)findViewById(R.id.rv_wishlist);
wishList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.civ_navprofilepicture);
NavProfileFirstName = (TextView)navView.findViewById(R.id.tv_headerfirstname);
NavProfileLastName = (TextView) navView.findViewById(R.id.tv_headerlastname);
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
if (dataSnapshot.hasChild("fornavn")){
String firstname = dataSnapshot.child("fornavn").getValue().toString();
NavProfileFirstName.setText(firstname);
}
if (dataSnapshot.hasChild("etternavn")) {
String lastname = dataSnapshot.child("etternavn").getValue().toString();
NavProfileLastName.setText(lastname);
}
if (dataSnapshot.hasChild("profilbilde")){
String image = dataSnapshot.child("profilbilde").getValue().toString();
Picasso.with(MainWishActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}
else{
Toast.makeText(MainWishActivity.this, "Profil navn finnes ikke...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ibaddnewwishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToWishListActivity();
}
});
DisplayUsersWishLists();
}
private void DisplayUsersWishLists() {
FirebaseRecyclerAdapter<WishListClass, WishListViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishListClass, WishListViewHolder>
(
WishListClass.class,
R.layout.wish_list_single_layout,
WishListViewHolder.class,
WishListRef
) {
#Override
protected void populateViewHolder(WishListViewHolder viewHolder, WishListClass model, final int position) {
final String Key = getRef(position).getKey();
viewHolder.setFornavn(model.getFornavn());
viewHolder.setDate(model.getDate());
viewHolder.setTitle(model.getTitle());
viewHolder.setProfilbilde(getApplicationContext(), model.getProfilbilde());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MainWishActivity.this, UserWishItemActivity.class);
profileIntent.putExtra("Key", Key);
startActivity(profileIntent);
}
});
}
};
wishList.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListViewHolder extends RecyclerView.ViewHolder{
View mView;
public WishListViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setFornavn (String fornavn){
TextView wishlist_name = (TextView) mView.findViewById(R.id.tv_firstnamelist);
wishlist_name.setText(fornavn);
}
public void setProfilbilde (Context ctx, String profilbilde){
CircleImageView image = (CircleImageView) mView.findViewById(R.id.civ_profilepicturelist);
Picasso.with(ctx).load(profilbilde).into(image);
}
public void setDate (String date){
TextView wishlist_date = (TextView) mView.findViewById(R.id.tv_publisheddatelist);
wishlist_date.setText(" " + date);
}
public void setTitle (String title){
TextView wishlist_title = (TextView) mView.findViewById(R.id.tv_wishlisttitle);
wishlist_title.setText(title);
}
}
private void SendUserToWishListActivity(){
Intent addNewPostIntent = new Intent(MainWishActivity.this, AddWishListActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence(){
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
SendUserToUserInfoAcitivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToUserInfoAcitivity(){
Intent setupIntent = new Intent(MainWishActivity.this, UserInfoActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainWishActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToFindFriendsActivity(){
Intent findfriendsIntent = new Intent(MainWishActivity.this, FindFriendsActivity.class);
findfriendsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(findfriendsIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector (MenuItem item){
switch (item.getItemId()){
case R.id.navbtn_addwishlist:
SendUserToWishListActivity();
break;
case R.id.navbtn_profile:
Toast.makeText(this, "Profil", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_home:
Toast.makeText(this, "Hjem", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_friends:
Toast.makeText(this, "Venner", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_findfriends:
SendUserToFindFriendsActivity();
break;
case R.id.navbtn_settings:
Toast.makeText(this, "Instillinger", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_logout:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
SecondActivity
public class UserWishItemActivity extends AppCompatActivity {
private TextView tvwishlisttitle;
private EditText etwishitem;
private Button btnaddwishitem;
private RecyclerView wishListitems;
private String currentUserID, databaseUserID;
private String Key, postRandomName;
private DatabaseReference WishListUsersClickRef, UsersRef, WishItemsRef, wishListRef,WishItemsRef1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_add_wish_item);
Key = getIntent().getExtras().get("Key").toString();
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishItemsRef = FirebaseDatabase.getInstance().getReference().child("Ønsker");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID).child(Key);
tvwishlisttitle = (TextView)findViewById(R.id.tv_userwishlisttitle);
etwishitem = (EditText)findViewById(R.id.et_wishitem);
btnaddwishitem = (Button)findViewById(R.id.btn_addwishitem);
btnaddwishitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
wishListitems = (RecyclerView)findViewById(R.id.rv_wishlistitems);
wishListitems.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishListitems.setLayoutManager(linearLayoutManager);
WishListUsersClickRef = FirebaseDatabase.getInstance().getReference("Ønskelister").child(currentUserID).child(Key);
WishListUsersClickRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String title = dataSnapshot.child("title").getValue().toString();
databaseUserID = dataSnapshot.child("uid").getValue().toString();
tvwishlisttitle.setText(title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DisplayWishListItems();
}
private void DisplayWishListItems() {
FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder>
(
WishItemClass.class,
R.layout.wish_list_item_layout,
WishListItemsViewHolder.class,
WishItemsRef.child(Key)
) {
#Override
protected void populateViewHolder(final WishListItemsViewHolder viewHolder, final WishItemClass model, final int position) {
viewHolder.setWishitemname(model.getWishitemname());
viewHolder.m1View.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserWishItemActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.endreslettjobb_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle(model.getWishitemname());
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
final Button btndelete = (Button)dialogView.findViewById(R.id.btn_delete);
btndelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WishItemsRef.removeValue();
}
});
return false;
}
});
}
};
wishListitems.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListItemsViewHolder extends RecyclerView.ViewHolder{
View m1View;
public WishListItemsViewHolder(#NonNull View itemView) {
super(itemView);
m1View = itemView;
}
public void setWishitemname (String wishitemname){
TextView wishitem_name = (TextView) m1View.findViewById(R.id.tv_wishitemname);
wishitem_name.setText(wishitemname);
}
public void setUid (String uid){
}
}
private void CreateWishlist() {
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = etwishitem.getText().toString().trim();
etwishitem.setText("");
wishListRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("wishitemname", wishlist);
WishItemsRef.child(Key).child(postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
AddItemActivity
private Spinner spwishlisttitle;
private Button btnsavewishlist;
private DatabaseReference UsersRef, wishListRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, currentUserID, postRandomName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_wish_list);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
spwishlisttitle = (Spinner) findViewById(R.id.sp_wishlisttitle);
btnsavewishlist = (Button) findViewById(R.id.btn_savewishlist);
btnsavewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
}
private void CreateWishlist() {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("date", saveCurrentDate);
postMap.put("title", wishlist);
postMap.put("profilbilde", userProfileImage);
postMap.put("fornavn", userFirstname);
wishListRef.child(currentUserID).child(currentUserID + postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(AddWishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddWishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(AddWishListActivity.this, MainWishActivity.class);
startActivity(mainIntent);
}
}
I have edited my question with my code.
Hope this is helpful.

The items not appear in recyclerview

I face a problem when I send a comment, that comment does not appear in RecyclerView, I have to go back and reopen Activity again to see my reply.
BlogSingleActivity.java
public class BlogSingleActivity extends AppCompatActivity {
private String mPost_key = null;
DatabaseReference mDatabase;
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDesc;
private TextView mBlogSingleUsername, mNumbersOfComments;
private TextView mBlogSingleDate;
private DatabaseReference ReplayDatabase;
private RecyclerView mReplayBlogList;
private TextView emptyView;
FirebaseRecyclerAdapter<Blog, BlogViewHolder> mAdapter;
private EditText mReplayText;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private DatabaseReference mDatabaseUser;
private Uri mImagUri = null;
private static final int GALLERY_REQUEST = 2;
private StorageReference mStorage;
private ImageButton mselectImage;
Button sendBTN;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPost_key = getIntent().getExtras().getString("blog_id");
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
ReplayDatabase = FirebaseDatabase.getInstance().getReference().child("Replay");
mBlogSingleDesc = findViewById(R.id.singleBlogDesc);
mBlogSingleTitle = findViewById(R.id.post_Tittle);
mBlogSingleImage = findViewById(R.id.singleBlogImage);
mBlogSingleUsername = findViewById(R.id.singleBlogUsername);
mBlogSingleDate = findViewById(R.id.singleBlogDate);
mNumbersOfComments = findViewById(R.id.numberofcomments);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mReplayBlogList = findViewById(R.id.replay_blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mReplayBlogList.setLayoutManager(layoutManager);
mReplayBlogList.setNestedScrollingEnabled(false);
emptyView = findViewById(R.id.empty_view);
chickitem();
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
mReplayText = findViewById(R.id.ReplayField);
mStorage = FirebaseStorage.getInstance().getReference();
mselectImage = findViewById(R.id.replayImageSelect);
sendBTN = findViewById(R.id.send_BTN);
getfirebaseData();
mProgress = new ProgressDialog(this);
mselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
sendBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startReplay();
getfirebaseData();;
disappearKeyboard();
mReplayText.getText().clear();
mselectImage.setImageResource(R.mipmap.add_btn);
mselectImage.setBackgroundColor(getResources().getColor(R.color.image_background_color));
}
});
mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_title = (String) dataSnapshot.child("tittle").getValue();
String post_desc = (String) dataSnapshot.child("desc").getValue();
String post_image = (String) dataSnapshot.child("image").getValue();
String post_username = (String) dataSnapshot.child("username").getValue();
Object post_date = dataSnapshot.child("date").getValue();
Blog timeStamp = new Blog();
timeStamp.setDate(post_date);
if (timeStamp.getDate() != null) {
String datee = timeStamp.getDate().toString();
long time = Long.parseLong(datee);
String timeAgo = TimeAgo.getTimeAgo(time);
mBlogSingleDate.setText(timeAgo);
}
mBlogSingleTitle.setText(post_title);
mBlogSingleDesc.setText(post_desc);
mBlogSingleUsername.setText(post_username);
Picasso.with(BlogSingleActivity.this)
.load(post_image)
.into(mBlogSingleImage);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void disappearKeyboard() {
InputMethodManager inputManager =
(InputMethodManager) this.
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private void startReplay() {
{
final String replay_val = mReplayText.getText().toString().trim();
//send date to firebase database
if (!TextUtils.isEmpty(replay_val) && mImagUri != null) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
StorageReference filepath = mStorage.child("Replay_Images").child(mImagUri.getLastPathSegment());
filepath.putFile(mImagUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (mAuth.getCurrentUser() != null) {
#SuppressWarnings("VisibleForTests") final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replayimage").setValue(downloadUrl.toString());
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
});
} else if ((!TextUtils.isEmpty(replay_val))) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
}
}
private void getfirebaseData() {
mAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.replay_row,
BlogViewHolder.class,
ReplayDatabase.child(mPost_key)
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, final Blog model, int position) {
viewHolder.setReplay(model.getReplay());
viewHolder.setReplayname(model.getReplayname());
viewHolder.setReplaydate(model.getReplaydate());
viewHolder.setReplayimage(getApplicationContext(), model.getReplayimage());
}
};
mReplayBlogList.setAdapter(mAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageView replay_imagee;
TextView recive_replay, post_replayname, post_replaydate;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setReplay(String replay) {
recive_replay = mView.findViewById(R.id.replay_text);
recive_replay.setText(replay);
}
public void setReplayname(String replayname) {
post_replayname = mView.findViewById(R.id.replayer_name_field);
post_replayname.setText(replayname);
}
public void setReplaydate(Object relaydate) {
post_replaydate = mView.findViewById(R.id.post_replaydate);
Blog timeStamps = new Blog();
timeStamps.setDate(relaydate);
if (timeStamps.getDate()!=null){
String dateee = timeStamps.getDate().toString();
long times = Long.parseLong(dateee);
String timeAgoo = TimeAgo.getTimeAgo(times);
post_replaydate.setText(timeAgoo);
}
}
public void setReplayimage(final Context ctx, final String replayimage) {
replay_imagee = mView.findViewById(R.id.replay_image);
Picasso.with(ctx).load(replayimage).networkPolicy(NetworkPolicy.OFFLINE).into(replay_imagee, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(replayimage).into(replay_imagee);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImagUri = result.getUri();
mselectImage.setImageURI(mImagUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void chickitem() {
final AtomicInteger count = new AtomicInteger();
ReplayDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long numChildren = dataSnapshot.child(mPost_key).getChildrenCount();
if (numChildren == 0) {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("لا توجد تعليقات");
mReplayBlogList.setVisibility(View.INVISIBLE);
mNumbersOfComments.setText("لا توجد تعليقات");
} else {
mNumbersOfComments.setText("" + numChildren);
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("التعليقات...");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
getfirebaseData();
}
#Override
public void onResume(){
super.onResume();
getfirebaseData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The screen looks like .
There are two comments. To see these comment I have to go back and reopen this Activity.
I'm not 100% sure about this, but I think you're missing the mReplayBlogList.notifyDataSetChanged(); after the line mReplayBlogList.setAdapter(mAdapter); in getfirebaseData().
Maybe you could give it a try. Let me know if it solved :)

RecyclerView not scrolling with firebase

I'm making a chat application that uses Firebase as a backend, but I'm having trouble getting the RecyclerView to scroll to the bottom of the list. I have a chatActivity that has the following methods:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Id = getIntent().getExtras().getString("matchId");
Pic = findViewById(R.id.displayImageMessages);
thoughtButton = findViewById(R.id.messageThought);
//SET MENU
menuButton = findViewById(R.id.messageMenu);
menuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
optionMenu = new PopupMenu(ChatActivity.this,menuButton);
optionMenu.getMenuInflater().inflate(R.menu.popup_menu2,optionMenu.getMenu());
optionMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(menuItem.getItemId() == R.id.one){
backtoMain();
return true;
}
else if (menuItem.getItemId() == R.id.two){
return true;
}
else if(menuItem.getItemId() == R.id.three){
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.signOut();
backtoMenu();
return true;
}
else{
return false;
}
}
});
optionMenu.show();
}
});
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
//LOAD PICTURE
URI = getIntent().getExtras().getString("displayPic");
Glide.with(this).load(URI).thumbnail(0.4f).into(Pic);
//RETRIEVE CHAT
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseUser = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserID).child("connections").child(Id).child("ChatId");
databaseChat = FirebaseDatabase.getInstance().getReference().child("chat");
getChatId();
mSendEditText = findViewById(R.id.messageText);
mSendButton = findViewById(R.id.send);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.ChatRecycler);
mRecyclerView.setNestedScrollingEnabled(true);
mRecyclerView.setHasFixedSize(false);
linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
mChatLayoutManager = linearLayoutManager;
mRecyclerView.setLayoutManager(mChatLayoutManager);
mChatAdapter = new ChatViewAdapter(getDataSetChat(),ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);
mRecyclerView.addItemDecoration(new VerticalSpaceItemDecoration(20));
}
and
private void getChatId() {
databaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
databaseChat = databaseChat.child(chatId);
getChatMessages();
linearLayoutManager.scrollToPositionWithOffset(resultsChat.size(),0);
Log.d("messageTAG",String.valueOf(mChatAdapter.getItemCount()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
and
private void getChatMessages() {
databaseChat.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()){
String message = null;
String createdbyuser = null;
long timestamp = 0;
if (dataSnapshot.child("text").getValue()!=null){
message = dataSnapshot.child("text").getValue().toString();
}
if (dataSnapshot.child("createdBy").getValue()!=null){
createdbyuser = dataSnapshot.child("createdBy").getValue().toString();
}
if (dataSnapshot.child("timestamp").getValue()!=null){
timestamp = Long.valueOf(dataSnapshot.child("timestamp").getValue().toString());
}
if (message!=null&&createdbyuser!=null){
Boolean currentUserBoolean = false;
if (createdbyuser.equals(currentUserID)){
currentUserBoolean = true;
}
ChatObject newMessage = new ChatObject(message,currentUserBoolean,timestamp);
resultsChat.add(newMessage);
mChatAdapter.notifyDataSetChanged();
}
//SETS VISABILITY OF THOUGHTS BUTTON IF CHAT SIZE IS ABOVE 10
if(resultsChat.size() > 10){
thoughtButton.setVisibility(View.VISIBLE);
}
}
}
I've tried various layoutManager.ScrollToPosition or adapter.ScrollToPosition etc, but I'd appreciate any thoughts you have on this problem?
Try using
mRecyclerView.scrollToPosition(resultsChat.size() - 1);
In databaseChat.addChildEventListener()
Like this :
ChatObject newMessage = new ChatObject(message,currentUserBoolean,timestamp);
resultsChat.add(newMessage);
mRecyclerView.scrollToPosition(resultsChat.size() - 1); //here
mChatAdapter.notifyDataSetChanged();

Starting same acticity in android studio

I have created an app in android studio and I have a java file name Login.java. In which I had checked a particular mpin entered by user exists in firebase real time database or not.
Now I want that in else loop mpin doesn't exists then it should remain on Login activity.
How can this be done?
public class Login extends AppCompatActivity {
String enteredmPINString;
EditText enteredmPin;
DatabaseReference rootref;
String contactfromPhoneLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button mLoginSubmit;
mLoginSubmit = (Button) findViewById(R.id.loginSubmit);
Bundle b = getIntent().getExtras();
if(b!=null){
contactfromPhoneLogin = b.getString("contacttoLogin");
Log.d("abcd",contactfromPhoneLogin);
}
rootref= FirebaseDatabase.getInstance().getReference("Employees").child(contactfromPhoneLogin).child("empmpin");
Log.d("abcd","Database reference reached");
// enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
// enteredmPINString = enteredmPin.getText().toString();
View.OnClickListener submitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
enteredmPINString = enteredmPin.getText().toString();
Log.d("abcd",enteredmPINString);
final Intent loginIntent = new Intent(Login.this,NavigationDrawer.class);
loginIntent.putExtra ("mPINtoNavigation",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
startActivity(loginIntent);
rootref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("abcd","onDatachange reached");
Log.d("abcd",enteredmPINString);
if(dataSnapshot.child(enteredmPINString).exists()){
Log.d("abcd","mpin exists");
Intent loginIntent = new Intent(Login.this,NavigationDrawer.class);
loginIntent.putExtra ("mPINtoNavigation",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
startActivity(loginIntent);
}
else{
Toast.makeText(Login.this,"Invalid mPIN!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mLoginSubmit.setOnClickListener(submitListener);
}
public void erp_site(View view){
Intent erpIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://web.nbccho.com/erp/"));
startActivity(erpIntent);
}
public void nbcc_site(View view){
Intent nbcc_siteIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nbccindia.com/nbccindia/index.jsp"));
startActivity(nbcc_siteIntent);
}
}
remove the intent in onClick();
View.OnClickListener submitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
enteredmPINString = enteredmPin.getText().toString();
Log.d("abcd",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);

Current fragment redirecting to previous activity after change data in Firebase

The current fragment is redirecting to the started activity after i change the data in Firebase. I need to change the visiblity of the button in ManageTeam fragment.The flow of the application is
LoginActivity -> MainActivity -> ManageTeam
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private MaterialEditText etEmail,etPassword;
private Button btnLogin,btnSignUp;
private FirebaseAuth firebaseAuth;
LinearLayout linearLayout;
private String role;
private User student;
private ProgressDialog progressDialog;
DatabaseReference databaseReference;
ValueEventListener valueEventListener;
private static String user_field = "user";
private static String pwd_field = "pwd";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Paper.init(this);
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setTitle("MTCHY");
progressDialog.setMessage("Login");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
etEmail = (MaterialEditText) findViewById(R.id.etLoginEmail);
etPassword = (MaterialEditText) findViewById(R.id.etLoginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnSignUp = (Button) findViewById(R.id.btnLoginSignUp);
firebaseAuth = FirebaseAuth.getInstance();
linearLayout = (LinearLayout) findViewById(R.id.loginLayout);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password))
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Please enter an email and password").setTitle("Warning").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
databaseReference = FirebaseDatabase.getInstance().getReference();
valueEventListener = databaseReference.child("Users").orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Paper.book().write(user_field,etEmail.getText().toString());
Paper.book().write(pwd_field,etPassword.getText().toString());
for(DataSnapshot userDataSnapshot : dataSnapshot.getChildren())
{
student = userDataSnapshot.getValue(User.class);
role = student.getUserRole();
if (role.equals("Player"))
{
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
if (role.equals("Captain"))
{
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(databaseError.getMessage()).setTitle("Database Error").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage()).setTitle("Login Error").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this,SignupActivity.class);
startActivity(intent);
}
});
String papsuser = Paper.book().read(user_field);
String pappwd = Paper.book().read(pwd_field);
System.out.println(papsuser);
System.out.println(pappwd);
if (papsuser != null && pappwd != null)
{
if(!TextUtils.isEmpty(papsuser) && !TextUtils.isEmpty(pappwd))
{
autoLogin(papsuser,pappwd);
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
databaseReference.removeEventListener(valueEventListener);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AHBottomNavigation bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem("Home", R.drawable.common_google_signin_btn_icon_dark_focused, R.color.colorBottomNavigationDisable);
AHBottomNavigationItem item2 = new AHBottomNavigationItem("Manage Team", R.drawable.common_google_signin_btn_icon_dark_focused, R.color.colorAccent);
AHBottomNavigationItem item3 = new AHBottomNavigationItem("Setting", R.drawable.common_google_signin_btn_icon_dark_focused,R.color.colorPrimary);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
bottomNavigation.setDefaultBackgroundColor(getResources().getColor(R.color.colorBackgroud));
bottomNavigation.setCurrentItem(0);
bottomNavigation.setAccentColor(getResources().getColor(R.color.colorPrimary));
bottomNavigation.setInactiveColor(getResources().getColor(R.color.colorAccent));
bottomNavigation.setForceTint(true);
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
AFragment aFragment = new AFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, aFragment).commit();
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
if(position == 0) {
AFragment aFragment = new AFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, aFragment).commit();
return true;
}
else if(position == 1 )
{
ManageTeam manageTeam = new ManageTeam();
getSupportFragmentManager().beginTransaction().replace(R.id.content,manageTeam).commit();
return true;
}
return false;
}
});
}
}
ManageTeam.java
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btn = (Button) getView().findViewById(R.id.btnJohn);
users = FirebaseDatabase.getInstance().getReference("Users");
value = users.orderByChild("email").equalTo("viginesjohn2#gmail.com").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot clubDataSnapshot : dataSnapshot.getChildren())
{
User user = clubDataSnapshot.getValue(User.class);
if (user.getHasTeam() == true)
{
btn.setVisibility(View.GONE);
}
if (user.getHasTeam() == false)
{
btn.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
users.removeEventListener(value);
}
Firebase
My firebase data
UI
Android UI
Based on the UI , the activity will start on Home. After i change the the hasTeam field to true or false in Firebase. The Fragment updates the UI but it will redirect back to Home Activity.

Categories

Resources