I create an application and use a BottomNavigationView in it and one of the fragments calls the other fragment through the adapter. I am trying to make the BottomNavigationView disappear when this fragment is called, for this I use setVisibility (). But the problem is that it doesn’t disappear, maybe someone can tell me what I’m doing wrong
BottomNavigationView:
public class ProfileFragment extends Fragment {
private ImageView avatar;
private TextView nickname, bio, website;
private FirebaseMethods mFirebaseMethods;
private Context mContext;
private AppBarLayout mAppBarLayout;
private Menu mMenu;
private RecyclerView mRecyclerView;
private FirebaseUser mCurrentUser;
private TextView followers, followings;
private BottomNavigationView mBottomNavigationView;
private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
private ActivityResultContracts.RequestMultiplePermissions mRequestMultiplePermissions= new ActivityResultContracts.RequestMultiplePermissions();
private DatabaseReference mDatabaseReference;
private DatabaseReference followingRef;
private DatabaseReference followersRef;
private ReadWritePermissions mReadWritePermissions;
private IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile2, container, false);
mContext = container.getContext();
mFirebaseMethods = new FirebaseMethods(mContext);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mBottomNavigationView = getActivity().findViewById(R.id.bottomNavigation);
followingRef = FirebaseDatabase.getInstance().getReference("Following");
followersRef = FirebaseDatabase.getInstance().getReference("Followers");
Toolbar toolbar = view.findViewById(R.id.toolbar);
mAppBarLayout = view.findViewById(R.id.app_bar);
mRecyclerView = view.findViewById(R.id.posts_recycler);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
loadPosts();
avatar = view.findViewById(R.id.profile_avatar);
nickname = view.findViewById(R.id.profile_nickname);
bio = view.findViewById(R.id.profile_bio);
website = view.findViewById(R.id.profile_website);
followers = view.findViewById(R.id.followers_count);
followings = view.findViewById(R.id.following_count);
setFollowingFollowers();
followers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
followings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
avatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mFirebaseMethods.getUserDataProfile(avatar, nickname, bio);
return view;
}
private void loadPosts()
{
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerOptions<Posts> options
= new FirebaseRecyclerOptions.Builder<Posts>()
.setQuery(mDatabaseReference.orderByChild("uid").equalTo(mCurrentUser.getUid()), Posts.class)
.build();
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
PostAdapter adapter = new PostAdapter(options, mContext, mReadWritePermissions);
mRecyclerView.setAdapter(adapter);
adapter.startListening();
}
private void setFollowingFollowers()
{
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
followersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followers.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
followingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followings.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
Use setVisibility(View.GONE) instead.
I had the same problem, for some reason it doesn't work, but in the docs they also use View.GONE.
EDIT: Use the method shown in the docs to hide/show BottomNavigationView depending on the Fragment.
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller,
#NonNull NavDestination destination, #Nullable Bundle arguments) {
if(destination.getId() == R.id.full_screen_destination) {
toolbar.setVisibility(View.GONE);
bottomNavigationView.setVisibility(View.GONE);
} else {
toolbar.setVisibility(View.VISIBLE);
bottomNavigationView.setVisibility(View.VISIBLE);
}
}
});
Use Navigation component like in this example.
I fixed this by using DataBinding and ObservableField for the visibility, I don't why it didn't work through the normal onDestinationChangedListener on the NavController, it just bluntly ignored that command, everything else in that block worked fine but not the visibility.
So an ObservableField in the databinding did the trick
android:visibility="#{hideBottomNav ? View.GONE : View.VISIBLE}"
And set the value to the observable field in the onDestinationChangedListener to your desired outcome
if(destination.id == R.id.navigation_your_notes){
hideBottomNav.set(true)
} else hideBottomNav.set(false)
Related
I had user shared preferences to get the current Uid or other Uid from realtime database. But I need to do the same without the use of shared preferences. This is for my ProfileActivity and I am using viewpager with three different fragments. The shared preferences show only the current user's profile even when searched for other user in the app.
The image attached is the output of the profile activity in my smartphone. The top bar containing the username and the logout button is of the profile activity and the rest below the blue banner is of the viewpager
public class ProfileActivity extends AppCompatActivity {
private ImageView logout;
private TextView post;
private FloatingActionButton floatingActionButton;
private TabLayout tabLayout;
private ViewPager viewPager;
private TextView username;
private FirebaseUser fUser;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
String profileId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
fUser = FirebaseAuth.getInstance().getCurrentUser();
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Users").child(Objects.requireNonNull(firebaseAuth.getUid()));
String data = getBaseContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
logout = findViewById(R.id.log_out);
username = findViewById(R.id.username);
floatingActionButton = findViewById(R.id.floatingActionButton);
post = findViewById(R.id.posts_account);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
VPAdapter vpAdapter = new VPAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
vpAdapter.addFragment(new Profile(), "Profile");
vpAdapter.addFragment(new MyPosts(), "Posts");
if (profileId.equals(fUser.getUid())){
vpAdapter.addFragment(new SavedPosts(), "Saved");
}
viewPager.setAdapter(vpAdapter);
getPostCount();
userInfo();
getSupportActionBar().hide();
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, PostActivity.class));
finish();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(ProfileActivity.this).create();
alertDialog.setTitle("Are you sure to logout?");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(ProfileActivity.this, StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
finish();
}
});
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
}
});
}
private void getPostCount() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int counter = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts posts = snapshot.getValue(Posts.class);
if (posts.getPublisher().equals(profileId)) counter ++;
}
post.setText(String.valueOf(counter));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
username.setText("#" + user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the profile activity
public class MyPosts extends Fragment {
private RecyclerView recyclerView;
private PostAdapter photoAdapter;
private List<Posts> myPhotoList;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_thoughts, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
recyclerView = view.findViewById(R.id.recycler_view_pictures);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
myPhotoList = new ArrayList<>();
photoAdapter = new PostAdapter(getContext(), myPhotoList);
recyclerView.setAdapter(photoAdapter);
myPhotos();
return view;
}
private void myPhotos() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myPhotoList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts post = snapshot.getValue(Posts.class);
if (post.getPublisher().equals(profileId)){
myPhotoList.add(post);
}
}
Collections.reverse(myPhotoList);
photoAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
the above is the code for the posts fragments inside the viewpager of the profile activity
public class Profile extends Fragment {
private CircleImageView imageProfile;
private TextView followers;
private TextView following;
private TextView fullname;
private TextView bio;
private CircleImageView verification;
private TextView usernamebottom;
private Button editProfile;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE).edit().clear().apply();
}
imageProfile = view.findViewById(R.id.image_profile);
verification = view.findViewById(R.id.verification_profile);
followers = view.findViewById(R.id.followers);
following = view.findViewById(R.id.following);
fullname = view.findViewById(R.id.full_name);
bio = view.findViewById(R.id.bio);
usernamebottom = view.findViewById(R.id.username_btm);
editProfile = view.findViewById(R.id.edit_profile);
getFollowersAndFollowingCount();
userInfo();
if (profileId.equals(fUser.getUid())){
editProfile.setText("Edit profile");
} else {
checkFollowingStatus();
}
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String btnText = editProfile.getText().toString();
if (btnText.equals("Edit profile")){
//Go to edit profile
startActivity(new Intent(getContext(), EditProfileActivity.class));
} else{
if (btnText.equals("follow")){
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).removeValue();
}
}
}
});
return view;
}
private void checkFollowingStatus() {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid()).child("following")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(profileId).exists()) {
editProfile.setText("following");
} else {
editProfile.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getFollowersAndFollowingCount() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Follow").child(profileId);
ref.child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followers.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ref.child("following").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
following.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user.getImageurl().equals("default")){
imageProfile.setImageResource(R.drawable.ic_empty_profile);
} else {
Picasso.get().load(user.getImageurl()).into(imageProfile);
}
usernamebottom.setText("#" + user.getUsername());
fullname.setText(user.getName());
bio.setText(user.getBio());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the user detail fragment also in the view pager of my profile activity
I have been trying to implement search using firestoreUI but when i run my code the logcat says that:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.firebase.ui.firestore.FirestoreRecyclerAdapter.startListening()' on a null object reference
at com.example.homebarberv1.Search.onStart(Search.java:93)
below is my code:
public class Search extends AppCompatActivity implements FirebaseAuth.AuthStateListener{
private EditText searchField;
private Button searchButton;
private RecyclerView searchRecyclerview;
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private FirestoreRecyclerAdapter<User, UsersViewHolder> adapter;
private String searchText;
static {
FirebaseFirestore.setLoggingEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_search);
searchField = findViewById(R.id.SearchField);
searchButton = findViewById(R.id.SearchButton);
searchRecyclerview = findViewById(R.id.SearchContainer);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setReverseLayout(true);
manager.setStackFromEnd(true);
searchRecyclerview .setHasFixedSize(true);
searchRecyclerview .setLayoutManager(manager);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.search);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
return true;
case R.id.appointment:
startActivity(new Intent(getApplicationContext(),HomePage.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(),Profile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = searchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
#Override
public void onStart() {
super.onStart();
if (isSignedIn()) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
FirebaseAuth.getInstance().removeAuthStateListener(this);
}
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth auth) {
if (isSignedIn()) {
adapter.startListening();
} else {
Toast.makeText(Search.this,"user are not signed in",Toast.LENGTH_LONG);
}
}
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
#NonNull
private void firebaseUserSearch(String searchText){
CollectionReference sCollection =
FirebaseFirestore.getInstance().collection("Barbers");
Query sQuery = sCollection.startAt(searchText).endAt(searchText + "\uf8ff");
FirestoreRecyclerOptions<User> options =
new FirestoreRecyclerOptions.Builder<User>()
.setQuery(sQuery, User.class)
.setLifecycleOwner(this)
.build();
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.searchlist, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull User model) {
holder.setName(model.getShopname());
holder.setPic(model.getPiclink());
holder.setAddress(model.getAddress() + ", " + model.getPostcode().toString() + ", " + model.getCity());
}
};
searchRecyclerview.setAdapter(adapter);
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
private View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.shopNameS);
userNameView.setText(name);
}
public void setPic(String link){
ImageView imageView = (ImageView)mView.findViewById(R.id.imageS);
Picasso.get().load(link).into(imageView);
}
public void setAddress(String address){
TextView addressView = (TextView) mView.findViewById(R.id.shopAddressS);
addressView.setText(address);
}
}
}
the error refers to this line:
adapter.startListening();
I'm still new to Android, so I do not really understand what I'm doing wrong here, help is really appreciated
You need to ensure that adapter has been given a value, before you call adapter.startListening on it.
That means that in onStart you need to ensure the adapter exists:
#Override
public void onStart() {
super.onStart();
if (isSignedIn() && adapter != null) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
And then also start listening on the adapter when you create it and the user is signed in. So:
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
...
});
if (isSignedIn()) {
adapter.startListening();
}
I am trying to pass a value from my activity to my fragment but I keep getting this error "attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference". I am not sure why, some help would be greatly appreciated.
Fragment class
public class MessageFragment extends Fragment {
private RecyclerView displayMessagesRecycleView;
private View displayChatListView;
private RecyclerView.LayoutManager layoutManager;
private ChatListAdapter chatListAdapter;
private ArrayList<String> messageList;
private Message message;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
displayChatListView = inflater.inflate(R.layout.display_messages_layout, container, false);
createObjects();
initRecycleView();
populateRecycleView();
return displayChatListView;
}
//set up RecycleVIew/listener to detect taps
public void initRecycleView() {
displayMessagesRecycleView = displayChatListView.findViewById(R.id.chatListRecycleView);
layoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) layoutManager).setStackFromEnd(true);
((LinearLayoutManager) layoutManager).setReverseLayout(true);
displayMessagesRecycleView.setLayoutManager(layoutManager);
chatListAdapter = new ChatListAdapter(getActivity(), messageList);
displayMessagesRecycleView.setAdapter(chatListAdapter);
displayMessagesRecycleView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, final int position) {
TextView textView = view.findViewById(R.id.textViewOptions);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("position", "item clicked");
}
});
}
})
);
}
#Override
public void onStart() {
super.onStart();
retreiveBundle();
}
//Instantiate objects
public void createObjects() {
messageList = new ArrayList<>();
}
public void populateRecycleView() {
messageList.add("HEy");
chatListAdapter.notifyDataSetChanged();
}
//retrieves selected user's name and profile pic from message activity and updates profile image and name
public void retreiveBundle() {
String data = getArguments().getString("data");// data whi
}
}
Message Activity
public class MessageActivity extends AppCompatActivity {
private RecyclerView messagesRecycleView;
private String userProfileName;
private String userProfilePic;
private String timeStamp;
private String messageTimeStamp;
private HashMap<String, Object> messageDictionary;
private FirebaseUser currentFirebaseUser;
private TextView userNameTextView;
private CircleImageView userProfilePicture;
private EditText messageInputEditText;
private DatabaseReference firebaseDatabase;
private DatabaseReference messesagesRef;
private DatabaseReference RootRef;
private String id;
private String messageSender, messageReceiver;
private Message messages;
private ArrayList<Message> messageList;
private MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
messageList = new ArrayList<>();
initRecycleView();
linkUpViews();
createObjects();
setUpFirebase();
retreiveBundle();
messageSender = currentFirebaseUser.getUid();
messageReceiver = id;
}
#Override
protected void onStart() {
super.onStart();
messageList.clear();
RootRef.child("Messages").child(messageSender).child(messageReceiver).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Message messages = dataSnapshot.getValue(Message.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//find views by id
public void linkUpViews() {
userNameTextView = findViewById(R.id.userNameTv);
userProfilePicture = findViewById(R.id.chatProfilePic);
messageInputEditText = findViewById(R.id.chatboxEditText);
}
//set up RecycleView
public void initRecycleView() {
messagesRecycleView = findViewById(R.id.messagesRecycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
messagesRecycleView.setLayoutManager(linearLayoutManager);
messageAdapter = new MessageAdapter(MessageActivity.this, messageList);
messagesRecycleView.setAdapter(messageAdapter);
}
//create objects
public void createObjects() {
messageDictionary = new HashMap<>();
//messageList = new ArrayList<>();
}
public void sendMessageButton(View view) {
sendMessages();
//saveMessages();
}
//retrieves selected user's name and profile pic from NewsFeedFragment and updates profile image and name
public void retreiveBundle() {
Bundle bundle = getIntent().getExtras();
userProfileName = bundle.getString("profileName");
userProfilePic = bundle.getString("profilePic");
timeStamp = bundle.getString("timestamp");
id = bundle.getString("id");
Log.i("timestamp", timeStamp);
userNameTextView.setText(userProfileName);
Picasso.get().load(userProfilePic).into(userProfilePicture);
}
//goes back to previous activity
public void backToShop(View view) {
Intent intent = new Intent(MessageActivity.this, MainActivity.class);
startActivity(intent);
}
//Set up Firebase connection
public void setUpFirebase() {
messesagesRef = FirebaseDatabase.getInstance().getReference();
RootRef = FirebaseDatabase.getInstance().getReference();
firebaseDatabase = FirebaseDatabase.getInstance().getReference();
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
}
//Store messages to Firebase
public void sendMessages() {
if (TextUtils.isEmpty(messageInputEditText.getText().toString())) {
Toast.makeText(this, "Please enter a message", Toast.LENGTH_SHORT).show();
} else {
String messageSenderRef = "Messages/" + messageSender + "/" + messageReceiver;
String messageReceiverRef = "Messages/" + messageReceiver + "/" + messageSender;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSender).child(messageReceiver).push();
String messagePushKey = userMessageKeyRef.getKey();
messageDictionary.put("message", messageInputEditText.getText().toString());
messageDictionary.put("sender", messageSender);
messageDictionary.put("receiver", messageReceiver);
HashMap<String, Object> messageBodyDetails = new HashMap<>();
messageBodyDetails.put(messageSenderRef + "/" + messagePushKey, messageDictionary);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushKey, messageDictionary);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
messageInputEditText.setText("");
Toast.makeText(MessageActivity.this, "Sent message...", Toast.LENGTH_SHORT).show();
sendDataToFrag();
} else {
Log.e("Error", task.getException().getMessage().toString());
}
}
});
}
}
//sends data to message fragment...
public void sendDataToFrag(){
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
MessageFragment fragobj = new MessageFragment();
fragobj.setArguments(bundle);
}
}
This code will work
public class MyFragment extends Fragment {
public static MyFragment newInstance(String data) {
Bundle args = new Bundle();
args.putString("data", data);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
public String getData() {
return getArguments().getString("data");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String data = getData();
return inflater.inflate(R.layout.test, container, false);
}
}
And you Activity must be like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uiView = findViewById(R.id.ui);
uiView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
#Override
public void run() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.fragment, MyFragment.newInstance("My Test"));
transaction.commit();
}
}).start();
}
});
}
}
i'm from indonesia, i want to refresh a fragment after i insert a data to it.. i have try many times to refresh a fragment. but it can't work.
please help me..
here's my code..
class MainActivity
public class MainActivity extends FragmentActivity {
public MainActivity() {
}
DatabaseReference dataBaseref;
StorageReference strRef;
TextView logout;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBaseref = FirebaseDatabase.getInstance().getReference();
strRef = FirebaseStorage.getInstance().getReference();
tabLayout = findViewById(R.id.tab_layout_isi_menu);
viewPager = findViewById(R.id.view_pager_isi_menu);
logout = findViewById(R.id.text_logout);
viewAdapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewAdapter.addFragment(new isi_list_beli(), "Beli");
viewAdapter.addFragment(new isi_list_cek(), "Cek Data");
viewPager.setAdapter(viewAdapter);
tabLayout.setupWithViewPager(viewPager);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logOut();
}
});
}
private void logOut() {
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
}
public void onBackPressed() {
super.finish();
}
}
class isi_list_cek
public class isi_list_cek extends Fragment {
private ListView listView;
public AdapterListCek adapterListCek = null;
private ArrayList<Cek> cekArrayList;
Cursor cursor;
View view;
FloatingActionButton fab;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
adapterListCek.notifyDataSetChanged();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #NonNull Bundle savedInstanceState) {
view = inflater.inflate(R.layout.list_barang, container, false);
listView = view.findViewById(R.id.list_item_barang);
fab = view.findViewById(R.id.tambah_barang);
cekArrayList = new ArrayList<>();
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
listView.setAdapter(adapterListCek);
cursor = fragment_input_data.sqlHelper.getData("SELECT * FROM CEK");
if(cursor.moveToFirst()){
cekArrayList.clear();
do{
int id = cursor.getInt(0);
String kode = cursor.getString(1);
String nama = cursor.getString(2);
String jumlah = cursor.getString(3);
String harga = cursor.getString(4);
byte[] gambar = cursor.getBlob(5);
cekArrayList.add(new Cek(id, kode, nama, harga, jumlah, gambar));
}while (cursor.moveToNext());
fragment_input_data.sqlHelper.close();
}
adapterListCek.notifyDataSetChanged();
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return false;
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), fragment_input_data.class));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
class ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentListTitle = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm, Context mContext) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentListTitle.size();
//return 2;
}
#NonNull
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
public void addFragment (Fragment fragment, String string){
fragmentList.add(fragment);
fragmentListTitle.add(string);
}
}
i expect when i insert some data, fragment will automatically update it's view.
call a function as: just send the new instance of present fragment that you want to recreate
replaceFragment(new YourPresentFragment());
the function can be as below:
private void replaceFragment(Fragment fragment) {
String fragmentTag = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragments, fragment, fragmentTag);
ft.addToBackStack("fragments");
ft.commit();
}
this should do the job
I am creating a Chat App and I show the user their contacts. Right now the user can see the image name and status of all of their contacts. But when the user clicks on the contact I want them to go into the ChatActivity. Right now I am stuck because I don't know how to send them their.
I tried this
mAuth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
But it doesn't work the words setOnClickListener are red. Can someone please help ?
EDIT !!!!!!
I tried both of the below answers and neither helped me. When I put these blocks
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
SendUserToChatActivity();
}
}
private void SendUserToChatActivity() {
Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
And I am getting a red line under here Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
This is the updated code(I am still trying to find a way).
private View ContactsView;
private RecyclerView myContactsList;
private DatabaseReference ContacsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
public ContactsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ContactsView = inflater.inflate(R.layout.fragment_contacts, container, false);
myContactsList = (RecyclerView) ContactsView.findViewById(R.id.contacts_list);
myContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ContacsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
return ContactsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContacsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ContactsViewHolder> adapter
= new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ContactsViewHolder holder, int position, #NonNull Contacts model) {
String userIDs = getRef(position).getKey();
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if(dataSnapshot.child("userState").hasChild("state")){
String state = (dataSnapshot.child("userState").child("state")).getValue().toString();
String date = (dataSnapshot.child("userState").child("date")).getValue().toString();
String time = (dataSnapshot.child("userState").child("time")).getValue().toString();
if(state.equals("online")){
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if(state.equals("offline")){
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
} else {
holder.userStatus.setText("offline");
}
if(dataSnapshot.hasChild("image")){
String userImage = dataSnapshot.child("image").getValue().toString();
String profileName = dataSnapshot.child("name").getValue().toString();
String profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
else{
String profileName = dataSnapshot.child("name").getValue().toString();
String profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ContactsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
SendUserToChatActivity();
}
}
private void SendUserToChatActivity() {
Intent mainIntent = new Intent(getApplication(), MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
}
};
myContactsList.setAdapter(adapter);
adapter.startListening();
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView userName, userStatus;
CircleImageView profileImage;
ImageView onlineIcon;
public ContactsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
}
}
Since you want recyclerView adapter clickable, you need to setOnClickListener in holder.itemView. Inside onBindViewHolder, add this
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ChatActivity.class);
i.putExtra("visit_user_id", userIDs);
i.putExtra("visit_user_name", profileName);
i.putExtra("visit_image", userImage);
startActivity(i);
}
});
Full Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ContactsView = inflater.inflate(R.layout.fragment_contacts, container, false);
myContactsList = (RecyclerView) ContactsView.findViewById(R.id.contacts_list);
myContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ContacsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
return ContactsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContacsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ContactsViewHolder> adapter
= new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ContactsViewHolder holder, final int position, #NonNull Contacts model) {
final String userIDs = getRef(position).getKey();
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = (dataSnapshot.child("userState").child("state")).getValue().toString();
String date = (dataSnapshot.child("userState").child("date")).getValue().toString();
String time = (dataSnapshot.child("userState").child("time")).getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
} else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
} else {
holder.userStatus.setText("offline");
}
if (dataSnapshot.hasChild("image")) {
userImage = dataSnapshot.child("image").getValue().toString();
profileName = dataSnapshot.child("name").getValue().toString();
profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);
} else {
profileName = dataSnapshot.child("name").getValue().toString();
profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ChatActivity.class);
i.putExtra("visit_user_id", userIDs);
i.putExtra("visit_user_name", profileName);
i.putExtra("visit_image", userImage);
startActivity(i);
}
});
}
#NonNull
#Override
public ContactsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
};
myContactsList.setAdapter(adapter);
adapter.startListening();
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView userName, userStatus;
CircleImageView profileImage;
ImageView onlineIcon;
public ContactsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
}
}
Looks like you only missing the proper import, you can press alt + enter on everything that is in red to import open small dialog and import it.
You can either import this:
import android.view.View.OnClickListener;
Or you can implement the click listener interface and avoid creating new click listener for every view like this:
class yourClass implements View.OnClickListener {
#Override
public void onClick(View v) {
//Views clicks go here
}
}
Edit:
You need to replace your first parameter in your intent and pass context.
Replace this:
Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
with this:
Intent mainIntent = new Intent(context, MainActivity.class);
Note that you will have to pass the context and not just the keyword "context", for example, you can pass your current activity like this:
Intent mainIntent = new Intent(MyActivityThatContainsThisFragment, MainActivity.class);
You must get the context of where it is at this moment in case it is a fragment.
Intent mainIntent = new Intent(**getContext()**, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
If you want to set click listener on list item then
import android.view.View.OnClickListener;
public static class ContactsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
...some other code
ContactsViewHolder(View itemView){
// some code
// setting click listener on complete row
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent i = new Intent(v.getContext(),ChatActivity.class);
v.getContext().startActivity(i);
}
EDIT :
For your ChatLink,
Intent require 2 parameter to open activity i.e. Context and Destination class. So try this
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
//Resolve error
// you can also use class of fragment i.e. Fragment.this.getContext()
SendUserToChatActivity(v.getContext());
}
}
private void SendUserToChatActivity(Context ctx) {
Intent mainIntent = new Intent(ctx, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}