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>
Related
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.
I am trying to create an app that will get some information from a server, using volley. You should enter your info in, and then click login at the bottom, but for somereason it keeps crashing.
First and foremost when the button is clicked, it crashes and the logcat is:
https://pastebin.com/deQi874r
Main Activity code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
TextView textView = (TextView)findViewById(R.id.currentFragDisplay);
textView.setText("My Profile");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer, new Personal_Profile_Fragment());
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbar_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
switch (item_id) {
case R.id.accDetails:
swapFragment(item_id);
return true;
case R.id.personalProfileLookup:
swapFragment(item_id);
return true;
case R.id.favoriteCharacters:
swapFragment(item_id);
return true;
case R.id.friendProfileLookup:
swapFragment(item_id);
return true;
case R.id.tipsAndTricks:
swapFragment(item_id);
return true;
}
return false;
}
private void swapFragment(int fragmentID){
TextView tracker = (TextView) findViewById(R.id.currentFragDisplay);
Fragment fragment = null;
if(fragmentID == R.id.personalProfileLookup) {
tracker.setText("My Profile");
fragment = new Personal_Profile_Fragment();
} else if(fragmentID == R.id.favoriteCharacters) {
tracker.setText("Favorite Characters");
fragment = new Favorite_Characters_Fragment();
} else if(fragmentID == R.id.friendProfileLookup) {
tracker.setText("Friend Lookup");
fragment = new Friend_Profile_Fragment();
} else if(fragmentID == R.id.tipsAndTricks) {
tracker.setText("Tips and Tricks");
fragment = new TipsandTricks_Fragment();
} else if(fragmentID == R.id.accDetails) {
tracker.setText("Log In");
fragment = new loginFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
login fragment(where button is):
public class loginFragment extends Fragment {
//Local Vars
private boolean loginCheck = false;
//required constructor
public loginFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
login(v);
}
});
// Inflate the layout for this fragment
return view;
}
public boolean isLoggedIn() {
return loginCheck;
}
private void login(View v){
Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_LONG).show();
String username;
String password;
username = v.findViewById(R.id.enteredUsername).toString();
password = v.findViewById(R.id.enteredPassword).toString();
final ArrayList<String> info = new ArrayList<>();
String[] unameSeparated = new String[username.length()];
unameSeparated = username.split("(?!^)");
String startUrl = "https://us.api.battle.net/d3/profile/";
String uname = "";
String APIKey = "/?locale=en_US&apikey=6nguxckrzchn86q9792jvdhww4uxf32v";
//Separating the username into the parts needed for sending request
for (int i = 0; i < unameSeparated.length; i++) {
if ((unameSeparated[i].equals("#"))) {
//Replacing # with '%23'
uname += "%23";
} else {
uname += unameSeparated[i];
}
}
String url = startUrl + uname+ APIKey;
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
info.add(response);
Toast.makeText(getActivity(),"Request Success",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Request FAIL",Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
}
The problem is with you login click. You are passing the button and not the view in
login(v);
The V you are passing is an instance of the button not the view. So this
username = v.findViewById(R.id.enteredUsername).toString();
password = v.findViewById(R.id.enteredPassword).toString();
would be refering to a null pointer. Hope this helps
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();
In my app I have the following navigationview.
So when the user click the menu item Καλώς ήρθες(meaning welcome in Greek),I want the this to be shown in the toolbar. This is my code for the navigationview.
public class Welcome extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private SessionManager session;
Toolbar toolbar;
private int mIconSize;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(getApplicationContext());
SharedPreferences userName = PreferenceManager.getDefaultSharedPreferences(this);
//UserId = userName.getString("id","");
username = userName.getString("user_name", "");
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
if (savedInstanceState == null) {
//Restore the fragment's instance and geo coordinates!
//homeFragment = (FragmentHome) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
setSelected(R.id.welcome);
}else{
//profileFragment = (FragmentProfile) fm2.findFragmentByTag(PROFILE_FRAGMENT);
}
ActionBarDrawerToggle adt = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.open_drawer,R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(adt);
adt.syncState();
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setBackgroundColor(getResources().getColor(R.color.navigation_bg_color));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
boolean result = setSelected(item.getItemId());
return result;
}
});
View v = navigationView.getHeaderView(0);
TextView t = (TextView)v.findViewById(R.id.username);
t.setText(username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.log_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
logoutUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(Welcome.this, MainActivity.class);
startActivity(intent);
finish();
}
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
WelcomeFragment welcomeFragment = new WelcomeFragment();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction fragmentTra1 = fm1.beginTransaction();
fragmentTra1.replace(R.id.content,welcomeFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra1.commit();
return true;
case R.id.general:
GeneralFragment generalFragment= new GeneralFragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction fragmentTra2 = fm2.beginTransaction();
fragmentTra2.replace(R.id.content,generalFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra2.commit();
return true;
case R.id.announcements:
AnnouncementsFragment announcementsFragment= new AnnouncementsFragment();
FragmentManager fm3 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubOne = fm3.beginTransaction();
fragmentTraSubOne.replace(R.id.content,announcementsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubOne.commit();
return true;
case R.id.sub_one:
NewsFragment newsFragment= new NewsFragment();
FragmentManager fm4 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubTwo = fm4.beginTransaction();
fragmentTraSubTwo.replace(R.id.content,newsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubTwo.commit();
return true;
case R.id.sub_two:
FanClubFragment fanClubFragment= new FanClubFragment();
FragmentManager fm5 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubThree = fm5.beginTransaction();
fragmentTraSubThree.replace(R.id.content,fanClubFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubThree.commit();
return true;
}
return false;
}
public static Intent newIntent(Context context) {
return new Intent(context,MainActivity.class);
}
#Override
public void onBackPressed() {
if(isNavDrawerOpen()){
closeDrawerLayout();
}else {
super.onBackPressed();
}
}
public boolean isNavDrawerOpen() {
return drawerLayout!=null && drawerLayout.isDrawerOpen(GravityCompat.START);
}
private void closeDrawerLayout(){
if(drawerLayout != null){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}
Any ideas?
Thanks,
Theo.
Try using setTitle():
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
toolbar.setTitle("Welcome");
......
}
.....
}
Try using:
getSupportActionBar().setTitle("title");
in the switch-case
I think you could use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Also this link might help: Here
Hope it helps ;)
btw your app looks great!
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!