Want to update user pic in nav drawer from device - android

I want when someone cliks google login and his/her profile pic,email and name appears on drawer just like pic below, there should also be an option to update profile so that he/she can replace that pic from the device storage selected. And also when next time user login that device pic will remain intact and shouldnt be replaced by google id pic.
Here is my MainActivity.java
import ...
public class MainActivity extends AppCompatActivity{
private FirebaseAnalytics mFirebaseAnalytics;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference();
private TextView mName;
private TextView mEmail;
private String name;
private String emailname;
private Uri photoUrl;
private ImageView mPic;
private NavigationView mNavigationView;
private static final int RC_SIGN_IN = 0;
public String TAG = "Main Activity";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Obtain the FirebaseAnalytics instance.
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mAuth = FirebaseAuth.getInstance();
//myRef.setValue("Hello World");
SectionsPagerAdapter mSectionPagerAdapter = new MainActivity.SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
if(mAuth.getCurrentUser()!=null)
{
Log.d("AUTH",mAuth.getCurrentUser().getEmail());
//user already signed in
}else {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build()))
.build(),
RC_SIGN_IN);
}
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.username);
mPic = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.imageView);
mEmail = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.email);
getCurrentUserInfo();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_gallery:
Toast.makeText(MainActivity.this,"My Profile Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_notifications:
Toast.makeText(MainActivity.this,"Notifications Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_liked_posts:
Toast.makeText(MainActivity.this,"Liked Post",Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_slideshow:
Toast.makeText(MainActivity.this,"Slideshow Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.log_out_button:
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d("AUTH","USER LOGGED OUT");
finish();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
default:
return true;
}
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RC_SIGN_IN){
if(resultCode==RESULT_OK){
//user logged in
Log.d("AUTH",mAuth.getCurrentUser().getEmail());
getCurrentUserInfo();
}
else {
//user not authenticated
Log.d("AUTH","NOT AUTHENTICATED");
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO: Do something when the user submits the search query.
Log.d(TAG, "onQueryTextSubmit: Text Submitted");
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.d(TAG, "onQueryTextChange: Text Changed");
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
/* if (id == R.id.action_search) {
return true;
} */
return super.onOptionsItemSelected(item);
}
/*/For logout activity in navigation bar
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.log_out_button) {
// Handle the action
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d("AUTH","USER LOGGED OUT");
finish();
}
});
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Polls pollTab = new Polls();
return pollTab;
case 1:
Facts factTab = new Facts();
return factTab;
case 2:
News newsTab = new News();
return newsTab;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
}
private void getCurrentUserInfo(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
for (UserInfo profile : user.getProviderData()){
String providerId = profile.getProviderId();
String uid = profile.getUid();
name = profile.getDisplayName();
photoUrl = profile.getPhotoUrl();
emailname = profile.getEmail();
mName.setText(name);
mEmail.setText(emailname);
if(name!=null && emailname!=null) {
myRef.child("Users").child(name).child("Email").setValue(emailname);
myRef.child("Users").child(name).child("UserId").setValue(uid);
}
if (photoUrl == null) {
Picasso.get()
.load(R.drawable.usericon)
.resize(6000,2000)
.centerInside()
.into(mPic);
}else {
Picasso.get()
.load(photoUrl.toString())
.resize(6000, 2000)
.centerInside()
.into(mPic);
}
}
}
}
}
My activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Suggest me way to do this. I tried on my own but failed. Thanks :)

Okay so i achieved this using bunch of if-else codes which i am sharing below.
Inintially i set flag to 0, and when logged user tries to open the app then flag is set to 1
public void getCurrentUserInfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
for (UserInfo profile : user.getProviderData()) {
String providerId = profile.getProviderId();
String uid = profile.getUid();
name = profile.getDisplayName();
if (flag!=1) {
photoUrl = profile.getPhotoUrl();
if (photoUrl == null) {
Picasso.get()
.load(R.drawable.usericon)
.resize(6000, 2000)
.transform(new CropCircleTransformation())
.centerInside()
.into(mPic);
} else {
Picasso.get()
.load(photoUrl.toString())
.resize(6000, 2000)
.transform(new CropCircleTransformation())
.centerInside()
.into(mPic);
}
}else{
DatabaseReference valueRef = myRef.child("Users").child(name);
valueRef.child("ProfileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String url = dataSnapshot.getValue(String.class);
photoUrl= Uri.parse( url );
if (photoUrl == null) {
Picasso.get()
.load(R.drawable.usericon)
.resize(6000, 2000)
.transform(new CropCircleTransformation())
.centerInside()
.into(mPic);
} else {
Picasso.get()
.load(photoUrl.toString())
.resize(6000, 2000)
.transform(new CropCircleTransformation())
.centerInside()
.into(mPic);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
emailname = profile.getEmail();
mName.setText(name);
mEmail.setText(emailname);
if (name != null && emailname != null) {
myRef.child("Users").child(name).child("Email").setValue(emailname);
myRef.child("Users").child(name).child("UserId").setValue(uid);
}
}
}
}
I have posted full code in my question this is just the edited part required to initiate my query. For any queries comment.

Related

Android - SearchView not working in fragment present in MainActivity

Hello so I have a MainActivity which consists of two fragments one is home and the other notifications.
When the app is opened by default the Home fragment is displayed.My app has a navigation bar which comes with an app bar by default where all the Menu Items are inflated.
My home fragment consists of Posts and in the app bar there's a search icon (SearchView) when i click it and search for something nothing happens.
HomeFragment.java
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private HomeFragment.OnFragmentInteractionListener mListener;
private RecyclerView rv;
private FirebaseAuth fba;
private List<PostActivity> postItems;
private FirebaseUser user;
private Toolbar toolbar;
private PostAdapter pa;
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
user = FirebaseAuth.getInstance().getCurrentUser();
fba = FirebaseAuth.getInstance();
// dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles");
rv =view.findViewById(R.id.rvPostItems);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rv.setLayoutManager(layoutManager);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postItems = new ArrayList<>();
rv.addItemDecoration(new DividerItemDecoration(rv.getContext(), DividerItemDecoration.VERTICAL));
loadPosts();
registerForContextMenu(rv);
return view;
}
public void loadPosts() {
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Posts");
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postItems.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PostActivity pac = ds.getValue(PostActivity.class);
postItems.add(pac);
pa = new PostAdapter(postItems, getActivity());
rv.setAdapter(pa);
pa.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_SHORT).show();
}
});
}
public void searchPosts(String query){
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Posts");
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postItems.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
PostActivity pac = ds.getValue(PostActivity.class);
if(pac.getDesc().toLowerCase().contains(query.toLowerCase())) {
postItems.add(pac);
}
pa = new PostAdapter(postItems, getActivity());
rv.setAdapter(pa);
pa.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.main,menu);
MenuItem searchPosts = menu.findItem(R.id.searchPosts);
SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchPosts);
/*searchView.setIconified(true);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));*/
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!TextUtils.isEmpty(s))
searchPosts(s);
else
loadPosts();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(!TextUtils.isEmpty(s))
searchPosts(s);
else
loadPosts();
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof HomeFragment.OnFragmentInteractionListener) {
mListener = (HomeFragment.OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements
,HomeFragment.OnFragmentInteractionListener
,NotificationFragment.OnFragmentInteractionListener{
private FirebaseAuth fba;
private FirebaseUser user;
private TextView welcomeUser;
private DatabaseReference dr;
private String name, thumb;
private Toolbar toolbar;
private MaterialSearchView msv;
private FloatingActionButton addPost;
private HomeFragment homeFragment;
private NotificationFragment notificationFragment;
private BottomNavigationView bnv;
private ImageView navImg;
private MenuItem itemToHide;
private Menu postsMenu = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fba = FirebaseAuth.getInstance();
/*if(!fba.getCurrentUser().isEmailVerified()){
fba.getCurrentUser().updateEmail(fba.getCurrentUser().getEmail());
fba.getCurrentUser().sendEmailVerification();
}*/
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Newsy");
addPost = findViewById(R.id.add_post_btn);
addPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,AddPost.class);
startActivity(intent);
}
});
if (!(fba.getCurrentUser().isEmailVerified()) || fba.getCurrentUser() == null) {
startActivity(new Intent(this, LoginScreen.class));
}
/*if(fba.getCurrentUser()==null ){
startActivity(new Intent(this,LoginScreen.class));
}*/
ConnectionDetector cd = new ConnectionDetector(this);
if(cd.isConnected()){
Toast.makeText(this,"Connection Established !",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Your phone is Offline,Check your connection !",Toast.LENGTH_LONG).show();
}
user = fba.getCurrentUser();
String id = user.getUid();
dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles").child(id);
//ConstraintLayout cl = (ConstraintLayout)findViewById(R.id.LoginScreen);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
if (drawer != null) {
drawer.addDrawerListener(toggle);
}
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
dr = FirebaseDatabase.getInstance().getReference().child("Chat_Profiles").child(fba.getCurrentUser().getUid());
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
View nav_header = navigationView.getHeaderView(0);
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
name = dataSnapshot.child("name").getValue().toString();
thumb = dataSnapshot.child("image").getValue().toString();
CircleImageView circle = (CircleImageView) nav_header.findViewById(R.id.navImg);
Picasso.get().load(thumb).placeholder(R.drawable.default_avatar).into(circle);
welcomeUser = (TextView) nav_header.findViewById(R.id.WelcomeUser);
welcomeUser.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(pappuLayout);
Menu menu = navigationView.getMenu();
MenuItem mt = menu.findItem(nav_gallery);
mt.setTitle("News 2");
MenuItem mt2 = menu.findItem(nav_camera);
mt2.setTitle("News 1");
MenuItem mt3 = menu.findItem(nav_sub);
mt3.setTitle("Subscribe !");
//FRAGMENTS MAIN PAGE
bnv = findViewById(R.id.bottomNavigationView2);
homeFragment = new HomeFragment();
replaceFragment(new HomeFragment());
bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.bottomHome) {
replaceFragment(homeFragment);
return true;
} else if (itemId == R.id.bottomNotification) {
notificationFragment = new NotificationFragment();
replaceFragment(notificationFragment);
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = fba.getCurrentUser();
String id = user.getUid();
SharedPreferences sp = getSharedPreferences("USER", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Current_User", id);
editor.apply();
Intent intent = new Intent(getBaseContext(), MyUnityPlugin.class);
intent.putExtra("id", id);
dr.child("onlineStatus").setValue("true");
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser user = fba.getCurrentUser();
dr.child("onlineStatus").setValue(ServerValue.TIMESTAMP);
}
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.LogOut) {
fba.signOut();
finish();
startActivity(new Intent(this,LoginScreen.class));
return true;
}else if(id==R.id.settings){
startActivity(new Intent(this,ProfileActivity.class));
return true;
}else if(id==R.id.users){
startActivity(new Intent(this,Users.class));
return true;
}else if(id==R.id.search){
startActivity(new Intent(this,Users.class));
return true;
} else if (id == R.id.notificationSettings) {
startActivity(new Intent(this, SettingsActivity.class));
//startActivity(new Intent(this,UnityPlayerActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
if (itemId == R.id.nav_gallery) {
fragment = new GalleryFrag();
} else if (itemId == R.id.nav_camera) {
fragment = new CameraFrag();
} else if (itemId == R.id.nav_sub) {
fragment = new Subscribe();
} else if (itemId == R.id.nav_chat) {
fragment = new Chat();
} else if (itemId == R.id.nav_send) {
Intent i = new Intent(MainActivity.this, UnityPlayerActivity.class);
startActivity(i);
}
//replacing the fragment
if (fragment != null) {
ConstraintLayout fl = (ConstraintLayout) findViewById(pappuLayout);
fl.removeAllViews();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(pappuLayout, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(drawer_layout);
if (drawer != null) {
drawer.closeDrawer(GravityCompat.START);
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private void replaceFragment(Fragment fragment){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.postPage,fragment);
ft.addToBackStack(null);
ft.commit();
}
}
main.xml (Menu XML file)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/search"
android:title="Search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_action_search"
android:iconTint="#fff"
app:showAsAction="ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:visible="false"
>
</item>
<item
android:id="#+id/searchPosts"
android:title="Search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_action_search"
android:iconTint="#fff"
app:showAsAction="ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"
>
</item>
<item
android:id="#+id/notificationSettings"
android:icon="#drawable/baseline_settings_applications_white_18dp"
android:orderInCategory="100"
android:title="Settings"
app:showAsAction="ifRoom">
</item>
<item
android:id="#+id/LogOut"
android:orderInCategory="100"
android:title="Log Out"
app:showAsAction="never" />
<item
android:id="#+id/settings"
android:title="My Profile! "
>
</item>
<item
android:id="#+id/users"
android:title="All users"
>
</item>
</menu>

I have added profile activity, then added a dynamic image profile and username. After i did that, the navigation buttons are not working at all

here is my java code
that is the java code, I have added navigation profile activity then run it after retrieving the image and user name from the firebase. the navigation buttons are no more clickable
public class OwnerDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth OwnerAuth;
private DatabaseReference OwnerRef;
private CircleImageView OwnNavProfileImge;
private TextView OwnNavProfileName;
String currentUserID;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OwnerAuth = FirebaseAuth.getInstance();
OwnerRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUserID = OwnerAuth.getCurrentUser().getUid();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//for the navigation drawer button to open and close
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
View navView = navigationView.inflateHeaderView(R.layout.nav_header_owner_drawer);
OwnNavProfileName = (TextView)navView.findViewById(R.id.NavOwnerUserName);
OwnNavProfileImge = (CircleImageView)navView.findViewById(R.id.NavOwnerProfileImage);
OwnerRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists()) {
if(dataSnapshot.hasChild("fullname"))
{
String fullname = dataSnapshot.child("fullname").getValue().toString();
OwnNavProfileName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(OwnerDrawer.this).load(image).placeholder(R.drawable.profile).into(OwnNavProfileImge);
}
else
{
Toast.makeText(OwnerDrawer.this, "Profile name does not exist...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = OwnerAuth.getCurrentUser();
if(currentUser == null)
{
SendUserTologinActivity();
}
else
{
CheckUserExistence();
}
}
// to see if the user validation and his authenticated so if not, the user will be send to the setup activity.
private void CheckUserExistence()
{
final String current_user_id = OwnerAuth.getCurrentUser().getUid();
OwnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity()
{
Intent setupIntent = new Intent(OwnerDrawer.this, OwnerSetup.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserTologinActivity() {
Intent loginIntent = new Intent(OwnerDrawer.this,OwnerLogin.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// To open the menu button
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_Home) {
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Profile) {
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Posting_Cars) {
Toast.makeText(this, "Post Cars", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Chat) {
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Edit_profile) {
Toast.makeText(this, "Edit Profile", Toast.LENGTH_SHORT).show();
}
else if (id == R.id.nav_Logout) {
OwnerAuth.signOut();
SendUserTologinActivity();
Toast.makeText(OwnerDrawer.this, "Logged Out Successfull...", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
To receive callbacks when the user taps a list item in the drawer, implement the OnNavigationItemSelectedListener and attach it to your NavigationView by calling setNavigationItemSelectedListener().
You need to attach the navigationView to listener
navigationView.setNavigationItemSelectedListener(this);
Hope this helps.

Adding List to Cloud Firebase - Android

I do everything according to great guides from Youtube. https://www.youtube.com/watch?v=W-L6Cr2WP18 - I recommend. Unfortunately, instead of activity, I use a fragment and I have an error.
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private String userEmail, userName;
private GoogleApiClient googleApiClient;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore rootRef;
private FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
firebaseAuth = FirebaseAuth.getInstance();
rootRef = FirebaseFirestore.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser == null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
private void signOut(){
Map<String, Object> map = new HashMap<>();
map.put("tokenId", FieldValue.delete());
rootRef.collection("users").document(userEmail).update(map).addOnSuccessListener(new OnSuccessListener<Void>(){
#Override
public void onSuccess(Void aVoid){
firebaseAuth.signOut();
if(googleApiClient.isConnected()){
Auth.GoogleSignInApi.signOut(googleApiClient);
}
}
});
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
firebaseAuth.addAuthStateListener(authStateListener);
}
#Override
protected void onStop() {
super.onStop();
if(googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//wybieranie fragmentu
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1Goals();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}
//replacing the fragment - zmienianie fragmentów
//Transakcja fragmentu to seria zmian dotyczących fragmentu, które chcemy wykonać w tym samym momencie
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
//przekazywanie wybranego fragmentu do interfejsu
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
//------------------------------------Top Menu----------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
//getting the search view from the menu
MenuItem searchViewItem = menu.findItem(R.id.menuSearch);
//getting search manager from systemservice
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//getting the search view
final SearchView searchView = (SearchView) searchViewItem.getActionView();
//you can put a hint for the search input field
searchView.setQueryHint("Czego wspólnie poszukamy?");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//by setting it true we are making it iconified
//so the search input will show up after taping the search iconified
//if you want to make it visible all the time make it false
searchView.setIconifiedByDefault(true);
//here we will get the search query
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//do the search here
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_button:
signOut();
return true;
case R.id.action_settings:
//settings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//------------------------------------------------------------------------------------------
Fragment:
public class DailyFragment extends Fragment{
Toast toast;
private FirebaseFirestore rootRef;
private CollectionReference dailyGoalsRef;
private String userEmail, userName;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_daily, container, false);
FloatingActionButton fab2 = layout.findViewById(R.id.fab2);
fab2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Zadania na dzisiaj");
final EditText editText = new EditText(getContext());
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
editText.setHint("Podaj cel");
editText.setHintTextColor(Color.GRAY);
builder.setView(editText);
builder.setPositiveButton("Utwórz", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nazwa_celu = editText.getText().toString().trim();
addGoalsList(nazwa_celu);
}
});
builder.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
return layout;
}
private void addGoalsList(String nazwa_celu){
String goalsListId = dailyGoalsRef.document().getId();
GoalsModel goalsModel = new GoalsModel(goalsListId, nazwa_celu, userName);
dailyGoalsRef.document(goalsListId).set(goalsModel).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "Lista celów stworzona pomyślnie!");
}
});
}
}
To solve this, change the following lines of code:
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
with
if(googleSignInAccount != null){
userEmail = googleSignInAccount.getEmail();
userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
This fields are already declared as global.
You are using in your fragment the following line of code:
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
Where the userEmail is null. This is happening because you are not passing the userEmail from the activity to the fragment. Just declaring it as a global variable does not solve the problem.
To solve this, create a method in your activity that returns the userEmail.
public String getUserEmail() {return userEmail;}
And in your fragment, create a String field String userEmail as global and call that method like this:
userEmail = ((MainActivity) getActivity()).getUserEmail();

Failed to convert value of type java.util.HashMap to boolean

I'm trying to detect the connection state of my app, but this is the Error am facing:
Failed to convert value of type java.util.HashMap to boolean
I am using Firebase. The error is on line:
boolean connected = dataSnapshot.getValue(Boolean.class);
So the Error comes in the OnDataFinishedLoading() method . Data was coming at first, but now I just want to detect the apps network connection. Below is my code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static String KEY_HEADLINES="headlines";
public static String KEY_DETAILS="details";
// private static final String TAG = "Ask Doctor App";
ProgressBar pb;
public List<NewsModel> newslist;
public NewsAdapter2 adapter;
private RecyclerView mRecyclerView;
private DatabaseReference mRef;
ImageView image_news;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call the array list
newslist = new ArrayList<NewsModel>();
pb = (ProgressBar) findViewById(R.id.progressBarNews);
image_news =(ImageView) findViewById(R.id.image_news);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Enabling offline capabilities
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// firebase initialisation......
mRef = FirebaseDatabase.getInstance().getReference("News");
// keep my data synced
mRef.keepSynced(true);
OnDataFinishedLoading();
// load data
//declare the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo netInfo = cm.getActiveNetworkInfo();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* if (isOnline()) {
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();
} else {
Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
.setAction("", null).show();
}
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();*/
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void OnDataFinishedLoading(){
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
boolean connected = dataSnapshot.getValue(Boolean.class);
if(connected) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void LoadData (DataSnapshot dataSnapshot){
System.out.println(dataSnapshot.getValue());
NewsModel news_model =dataSnapshot.getValue(NewsModel.class);
newslist.add(news_model);
adapter = new NewsAdapter2(MainActivity.this, newslist);
mRecyclerView.setAdapter(adapter);
}
/* protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
*/
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}*/
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.hospitals) {
i = new Intent(MainActivity.this, HealthCentres.class);
startActivity(i);
} else if (id == R.id.doctors) {
i = new Intent(MainActivity.this, Doctors.class);
startActivity(i);
} /*else if (id == R.id.location) {
i = new Intent(MainActivity.this, Location.class);
startActivity(i);
} */else if (id == R.id.tips) {
i = new Intent(MainActivity.this, Tips.class);
startActivity(i);
} /*else if (id == R.id.faq) {
}
*/
/*
else if (id == R.id.suggestions) {
}
*/
else if (id == R.id.contacts) {
i= new Intent(MainActivity.this, ContactUs.class);
startActivity(i);
}
/*
else if (id == R.id.settings) {
}
*/
else if (id == R.id.about) {
i = new Intent(MainActivity.this, AboutUs.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Ok, so the core problem you're having is that Firebase is returning a Map, not a Boolean. That's because of the way you have this configured--every time a child is added, you try to look at the DataSnapshot (that's what the listener you setup does), and tries to get a Boolean value out. However, the Snapshot is the child added to the database (and not a boolean) so instead you get a map out.
If all you want to do is verify that a child was added successfully, I'd do the following:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object value = dataSnapshot.getValue();
if(value != null) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
However, this isn't really going to solve your network connectivity problem. It'll just do stuff whenever a non-null child gets added to the firebase object, which could happen frequently. Also in LoadData, you don't check to make sure that the object passed in isn't null.

viewpager didn't load the first page at the first time, but will load it after swipe to the last page

I am new to Android development and I don't have too much SO coins.
Basically, my project has a main screen activity and it contains 3 tabs, which are MyGiftsFragment, FriendsGiftsFragment and AboutMeFragment. I implemented tablayout and viewpager here. The problem is when I sign in the app, the first page(MyGiftsFragment) is empty, not loading anything(sometimes it loaded.) But when I swiped to the last tab(AboutMeFragment) and come back to the first tab, the content will be loaded. And this only works when I swiped to the last tab.
Due to my limit English, I am not sure if I explain the question clear. If you need any further information, please comment. I've searched the "setUserVisibleHint" and "setOnPageChangeListener(pageChangeListener)", but it seems that they are not what I want. Any advice will be appreciated. Thank you so much.
Here are my MainScreenActivity code.
public class MainScreenActivity extends AppCompatActivity {
private static final String TAG = MainScreenActivity.class.getName();
FirebaseAuth mAuth;
private DrawerLayout mDrawerLayout;
private FloatingActionButton fab;
private ArrayList<Gift> mGiftArray;
private RecyclerView mRecyclerView;
private boolean doubleBackToExitPressedOnce = false;
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplication().getApplicationContext());
mAuth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_main_screen);
/** Setup Toolbar and ActionBar. */
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
/** Setup DrawerLayout. */
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
/** 1.Setup drawer header content: Title and profile picture. */
View drawerHeader = navigationView.getHeaderView(0);
NetworkImageView drawerPicture = (NetworkImageView) drawerHeader.findViewById(R.id.drawer_picture);
NetworkImageView coverPicture = (NetworkImageView) drawerHeader.findViewById(R.id.cover_picture);
/** Fetch data from SharePreferences. */
SharedPreferences mSharedPreferences = this.getSharedPreferences("test", Activity.MODE_PRIVATE);
String drawerPictureUrl = mSharedPreferences.getString("picture", "");
String coverPictureUrl = mSharedPreferences.getString("cover", "");
ImageLoader imageLoader = MySingleton.getInstance(MainScreenActivity.this.getApplicationContext()).getImageLoader();
drawerPicture.setImageUrl(drawerPictureUrl, imageLoader);
coverPicture.setImageUrl(coverPictureUrl, imageLoader);
/** 2.Setup drawer body content: Name, E-mail and birthday. */
/** Fetch data from SharePreferences. */
String username = mSharedPreferences.getString("username", "");
String email = mSharedPreferences.getString("email", "");
String birthday = mSharedPreferences.getString("birthday", "");
Menu menu = navigationView.getMenu();
MenuItem nav_name = menu.findItem(R.id.navigation_item_name);
nav_name.setTitle(username);
MenuItem nav_email = menu.findItem(R.id.navigation_item_email);
nav_email.setTitle(email);
MenuItem nav_birthday = menu.findItem(R.id.navigation_item_birthday);
nav_birthday.setTitle(birthday);
/** Setup item onSelectedListener. */
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Intent intent;
if (menuItem.getItemId() == R.id.navigation_item_name) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_email) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_birthday) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_payment) {
mDrawerLayout.closeDrawers();
intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
startActivity(intent);
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_refresh) {
mDrawerLayout.closeDrawers();
finish();
startActivity(getIntent());
return true;
}
if (menuItem.getItemId() == R.id.navigation_item_logout) {
mDrawerLayout.closeDrawers();
facebookLogout();
return true;
}
return false;
}
});
/** Setup FloatingActionButton. */
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddGiftsActivity.class);
context.startActivity(intent);
}
});
TabPagerAdapter adapter = new TabPagerAdapter(this, getSupportFragmentManager());
final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
animateFab(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//
// viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// #Override
// public void onPageSelected(int position) {
// // do your work
// }
// });
}
private void animateFab(int position) {
switch (position) {
case 0:
fab.show();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddGiftsActivity.class);
context.startActivity(intent);
}
});
break;
case 1:
fab.show();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddGiftsActivity.class);
context.startActivity(intent);
}
});
break;
default:
fab.hide();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
return true;
case R.id.action_logout:
facebookLogout();
}
return super.onOptionsItemSelected(item);
}
static class TabPagerAdapter extends FragmentStatePagerAdapter {
private Context mContext;
public TabPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public Fragment getItem(int position) {
if (position == 0) {
return new MyGiftsFragment();
} else if (position == 1) {
return new FriendsGiftsFragment();
} else {
return new AboutMeFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return mContext.getString(R.string.my_gifts);
} else if (position == 1) {
return mContext.getString(R.string.friends_gifts);
} else {
return mContext.getString(R.string.about_me);
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void facebookLogout() {
if (mAuth.getCurrentUser() != null) {
Log.e("22", "Not sign out yet.");
} else {
Log.e("22", "Signed out already.");
}
mAuth.signOut();
if (mAuth.getCurrentUser() != null) {
Log.e("22", "Not sign out yet.");
} else {
Log.e("22", "Signed out already.");
}
LoginManager.getInstance().logOut();
Log.e("facebook", "logout");
startActivity(new Intent(MainScreenActivity.this, FacebookLoginActivity.class));
finish();
}
}
And here is MyGiftsFragment
public class MyGiftsFragment extends Fragment {
private static final String TAG = MyGiftsFragment.class.getName();
private ArrayList<Gift> mGiftArray;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private DatabaseReference mDatabase;
private String facebookId;
public MyGiftsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mGiftArray = new ArrayList<>();
SharedPreferences mSharedPreferences = this.getActivity().getSharedPreferences("test", Activity.MODE_PRIVATE);
facebookId = mSharedPreferences.getString("facebookId", "");
mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference myWishList = mDatabase.child("user/" + facebookId + "/my_gift/" + "/wish_list");
myWishList.addChildEventListener(new ChildEventListener() {
/** Add new gift */
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mGiftArray.clear();
/** com.jluo80.amazinggifter.MyGiftsFragment:-KMa77KnGU5hsF8dngVc*/
final String uniqueKey = dataSnapshot.getKey();
Log.e(TAG, "onChildAdded:" + uniqueKey);
/** com.jluo80.amazinggifter.MyGiftsFragment:true */
Log.e(TAG, "onChildAdded:" + dataSnapshot.getValue());
DatabaseReference ref = mDatabase.child("gift").child(uniqueKey);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot item) {
Log.e(TAG, "Single" + item.getKey());
System.out.println("test" + item.getValue());
Gift gift = item.getValue(Gift.class);
gift.setUnique_key(uniqueKey);
System.out.println(gift.getInitiator_id() + "&&&&&&&" + gift.getReceiver_id());
String end = gift.getDue_date();
String start = getCurrentDate();
if(gift.getProgress() <= gift.getPrice() && end.compareTo(start) >= 0) {
mGiftArray.add(gift);
mRecyclerView.setAdapter(new MyGiftRecyclerAdapter(getContext(), mGiftArray));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
});
DatabaseReference fromFriendsList = mDatabase.child("user/" + facebookId + "/my_gift/" + "/from_friends");
fromFriendsList.addChildEventListener(new ChildEventListener() {
/** Add new gift */
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// mGiftArray.clear();
/** com.jluo80.amazinggifter.MyGiftsFragment:-KMa77KnGU5hsF8dngVc*/
final String uniqueKey = dataSnapshot.getKey();
Log.e(TAG, "onChildAdded:" + uniqueKey);
/** com.jluo80.amazinggifter.MyGiftsFragment:true */
Log.e(TAG, "onChildAdded:" + dataSnapshot.getValue());
DatabaseReference ref = mDatabase.child("gift/" + uniqueKey);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot item) {
Log.e(TAG, "Single" + item.getKey());
System.out.println("test" + item.getValue());
Gift gift = item.getValue(Gift.class);
gift.setUnique_key(uniqueKey);
System.out.println(gift.getInitiator_id() + "&&&&&&&" + gift.getReceiver_id());
String end = gift.getDue_date();
String start = getCurrentDate();
if(gift.getProgress() <= gift.getPrice() && end.compareTo(start) >= 0) {
mGiftArray.add(gift);
mRecyclerView.setAdapter(new MyGiftRecyclerAdapter(getContext(), mGiftArray));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
});
return rootView;
}
public String getCurrentDate() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("MM/dd/yy");
return mdformat.format(calendar.getTime());
}
}
Please add this line before setting adapter. This will fix the issue
viewPager.setOffscreenPageLimit(3);
Offscreen page limit will decide how many adjacent pages need to be loaded when you see a page. So in your case set it to 3 (all pages).
Then your code will change to,
final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3); //Add this
viewPager.setCurrentItem(0);
Good luck!

Categories

Resources