When I tap on any item of in navigation drawer ,instead of going to new activity , the drawer toggles.
MainActivity :
public class MainActivity extends AppCompatActivity {
LinearLayoutManager mLayoutManager; //for sorting
SharedPreferences mSharedPreferences; //for saving sort setting
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
Toolbar toolbar;
RecyclerView mRecyclerView;
List<FoodData> myFoodList;
FoodData mFoodData;
MyAdapter myAdapter;
SearchView searchView;
private boolean ascending = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setUpToolbar();
// getSupportActionBar().hide();
toolbar =(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//menu hooks
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.navigation_menu);
toggle = new ActionBarDrawerToggle(this, drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
searchView = findViewById(R.id.srch);
mSharedPreferences= getSharedPreferences("SortSettings", MODE_PRIVATE);
String mSorting =mSharedPreferences.getString("Sort","newest"); // where if no setting is selected newest will be default
if(mSorting.equals("newest")){
mLayoutManager = new LinearLayoutManager(this);
//this will load the items from bottom means newest first
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
}else if(mSorting.equals("oldest")){
mLayoutManager = new LinearLayoutManager(this);
//this will load the items from bottom means oldest first
mLayoutManager.setReverseLayout(false);
mLayoutManager.setStackFromEnd(false);
}
//for setting company name in the navigation drawer
// navigationView=(NavigationView)findViewById(R.id.navigation_menu);
//navigationView.setNavigationItemSelectedListener(this);
// View header = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_favourite:
Intent intent = new Intent(MainActivity.this, favourite.class);
startActivity(intent);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_about_us:
Intent intent1 = new Intent(MainActivity.this , About_us.class);
startActivity(intent1);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_rate_us:
Intent intent2 = new Intent(MainActivity.this , RateUs.class);
startActivity(intent2);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_share:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "http://play.google.com/store/apps/detail?id=" + getPackageName();
String shareSub = "Try now";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
//drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_setting:
Intent intent3 = new Intent(MainActivity.this , SettingsActivity.class);
startActivity(intent3);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
}
return true;
}
});
GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this,1);
mRecyclerView.setLayoutManager(mLayoutManager);
myFoodList = new ArrayList<>();
mFoodData = new FoodData("Rawa Kesar",R.drawable.rawa,"INGREDIENTS");
mFoodData = new FoodData("Jalebi",R.drawable.jalebi,"INGREDIENTS");
mFoodData = new FoodData("Rasmalai",R.drawable.rasmlai,"INGREDIENTS");
mFoodData = new FoodData("Kaju Katli",R.drawable.kajuktli,"INGREDIENTS");
myAdapter = new MyAdapter(MainActivity.this,myFoodList);
mRecyclerView.setAdapter(myAdapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
myAdapter.getFilter().filter(s.toString());
return false;
}
});
}
// public void btn_uploadActivity(View view) {
//
// startActivity(new Intent(this,Upload_Recipe));
// }
// public void setUpToolbar() {
// drawerLayout = findViewById(R.id.drawerLayout);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
// drawerLayout.addDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.black));
// actionBarDrawerToggle.syncState();
//
// }
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id=item.getItemId();
if(id==R.id.sort){
//display alert dialogue to choose sorting
showSortDialogue();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showSortDialogue() {
//options to display in dialogue
String[] sortOptions = {"Newest","Oldest"};
//create alert dislogue
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setTitle("Sort By").setIcon(R.drawable.sort_2).setItems(sortOptions,new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
SharedPreferences.Editor editor=mSharedPreferences.edit();
editor.putString("Sort","newest");
editor.apply();
recreate();
}else if(which==1){
SharedPreferences.Editor editor=mSharedPreferences.edit();
editor.putString("Sort","oldest");
editor.apply();
recreate();
}
}
}
);
builder.show();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu,menu);
// MenuItem menuItem=menu.findItem(R.id.search);
// //SearchView searchView=(SearchView) menuItem.getActionView();
// searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// #Override
// public boolean onQueryTextSubmit(String s) {
// return false;
// }
//
// #Override
// public boolean onQueryTextChange(String s) {
// myAdapter.getFilter().filter(s.toString());
// return false;
// }
// });
// return super.onCreateOptionsMenu(menu);
// }
#Override
public void onBackPressed() {
Intent a =new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
}
this is my mainActiviy.xml code where i have usedNavigation View
I have checked my code many times but not able to find the mistake...it would be great help if someone helps me in this
Thanks in advance.
add navigation view below linear layout, it will work. In drawer layout , content should be first then navigation view.
Related
i want to parse json data title into my tabLayout. i have two fragment for that, and now i want to get only title from my json data. currently i set manual tab title in MainActivity.java file. how i can parse json data into my tabLayout?
here is my MainActivity.java code:
public class MainActivity extends AppCompatActivity implements Home.OnFragmentInteractionListener,
Politics.OnFragmentInteractionListener {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
Toolbar toolbar;
Dialog Developer;
TextView txtclose;
TextView facebook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(0xFF0F0E37);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
viewPager = (ViewPager)findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Home(),"Bangla");
viewPagerAdapter.addFragments(new Politics(),"Politics");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
Developer = new Dialog(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.about:
Developer.setContentView(R.layout.about);
txtclose =(TextView) Developer.findViewById(R.id.txtclose);
facebook = (TextView) Developer.findViewById(R.id.facebook);
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView facebook = (TextView) findViewById(R.id.facebook);
Intent openFB = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://facebook.com/test/"));
startActivity(openFB);
}
});
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Developer.dismiss();
}
});
Developer.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Developer.show();
break;
case R.id.share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
String shareTitile ="test";
String shareLink = "https://play.google.com/store/apps/details?id=test";
intent.putExtra(Intent.EXTRA_SUBJECT, shareTitile);
intent.putExtra(Intent.EXTRA_TEXT, shareLink);
startActivity(Intent.createChooser(intent, "Share test"));
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
here is my ViewPagerAdapter.java code:
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = (new ArrayList<>());
ArrayList<String> tabTitles = (new ArrayList<>());
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int possition) {
return fragments.get(possition);
}
#Override
public int getCount() {
return fragments.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
spouse, my json string is name. i want to parse that name into viewPagerAdapter.addFragments(new Home(),"Bangla"); and viewPagerAdapter.addFragments(new Politics(),"Politics");. here i want to replace Bangla to retrieve json data name and also replace Politics automatically from name. and i want to keep my 2 different fragments, because of - i will parse different data into both fragments.
i'm parsing josn from url as like https://website.com/api/details.php
here is my json response:
[
{"cid":"1","name":"Bangle"},
{"cid":"2","name":"Politics"},
{"cid":"3","name":"International"}
]
if you not understand my question, just let me know.
note: for better understanding, you can edit my code and post your answer!
thanks in advance.
public class MainActivity extends AppCompatActivity implements Home.OnFragmentInteractionListener,
Politics.OnFragmentInteractionListener {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
Toolbar toolbar;
Dialog Developer;
TextView txtclose;
TextView facebook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(0xFF0F0E37);
String jsonStr = ""; // this variable should contain the JSON response from url, assing json response to this variable.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
// If you have only two fragments then simply take a count variable other wise you can save this "name" in string array.
if(i==0){
viewPagerAdapter.addFragments(new Home(),name);
}else if(i == 1){
viewPagerAdapter.addFragments(new Politics(),name);
}
}
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
viewPager = (ViewPager)findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Home(),"Bangla");
viewPagerAdapter.addFragments(new Politics(),"Politics");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
Developer = new Dialog(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.about:
Developer.setContentView(R.layout.about);
txtclose =(TextView) Developer.findViewById(R.id.txtclose);
facebook = (TextView) Developer.findViewById(R.id.facebook);
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView facebook = (TextView) findViewById(R.id.facebook);
Intent openFB = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://facebook.com/test/"));
startActivity(openFB);
}
});
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Developer.dismiss();
}
});
Developer.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Developer.show();
break;
case R.id.share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
String shareTitile ="test";
String shareLink = "https://play.google.com/store/apps/details?id=test";
intent.putExtra(Intent.EXTRA_SUBJECT, shareTitile);
intent.putExtra(Intent.EXTRA_TEXT, shareLink);
startActivity(Intent.createChooser(intent, "Share test"));
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Nothing happens when I click on the items "Orders" and "Logout" from my navigation drawer:
Here's my code for the navigation drawer:
public class Home extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(Home.this, Cart.class);
startActivity(cartIntent);
}
});
final DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
menuItem.setChecked(true);
drawer.closeDrawers();
int id = menuItem.getItemId();
if (id == R.id.nav_menu) {
Toast.makeText(Home.this, "menu Clicked", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_cart) {
Intent cartIntent = new Intent(Home.this, Cart.class);
startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
// Toast.makeText(Home.this, "Order Clicked", Toast.LENGTH_SHORT).show();
Intent orderIntent = new Intent(Home.this, OrderStatus.class);
startActivity(orderIntent);
} else if (id == R.id.nav_logout) {
//Logout
Intent signIn=new Intent(Home.this,SignIn.class);
signIn.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(signIn);
}
return true;
}
});
//set name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView) headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//load menu
recycler_menu = findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private void loadMenu() {
FirebaseRecyclerOptions<Category> options = new FirebaseRecyclerOptions.Builder<Category>()
.setQuery(category, Category.class)
.build();
adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item, parent, false);
return new MenuViewHolder(itemView);
}
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder viewHolder, int position, #NonNull Category model) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent foodList = new Intent(Home.this, FoodList.class);
foodList.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(foodList);
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#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.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
super.onSupportNavigateUp();
}
}
I've tried to add toast in the nav_orders to check when I click orders it toast up but didn't work too, Code I've tried is :
else if (id == R.id.nav_orders) {
Toast.makeText(Home.this, "Order Clicked", Toast.LENGTH_SHORT).show();
}
If you have orders and logouts as items not under groups in drawer_menu you can create onClickListner for them. Don't call them by using if condition. You can directly place them under public boolean onNavigationItemSelected(#NonNull MenuItem item).
This sholud look like:
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
toolbar.setTitle("Ongoing Events");
break;
case R.id.nav_category:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HistoryFragment()).commit();
toolbar.setTitle("History");
break;
case R.id.Orders:
Toast.makeText(MainActivity.this, "Orders", Toast.LENGTH_SHORT).show();
case R.id.nav_logout:
AlertDialog.Builder builder = new AlertDialog.Builder(
(MainActivity.this));
builder.setTitle("Logout?");
builder.setMessage("Are you sure you want to sign out?");
builder.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
builder.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
logout();
restart();
}
});
builder.show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
I have built a bottom navigation tab bar in android,it has 5 fragments but the problem is on start of the application it doesn't load the recyclerview list from firestore database. and this fragment is Home Fragment. but if I randomly open another tab and then comes the to the home tab the home tab list loads itself, but it does not load automatically on start of the app
below is the code.
please assist
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "DocSnippets";
private FirebaseAuth mauth;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference UsersRef = db.collection("Users");
private DocumentReference noteRef = db.document("Notebook/My First Note");
private MySharedPreferences sp;
private DocumentReference currentUserRef;
private Button notificationList;
private String mUserId, tokenId, currentUserProfilePic, currentUserName, currentUserSpinnerC;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = MySharedPreferences.getInstance(this);
setContentView(R.layout.activity_main);
mauth = FirebaseAuth.getInstance();
// currentUserID = mauth.getCurrentUser().getUid();
UsersRef =FirebaseFirestore.getInstance().collection("Users");
mUserId = mauth.getUid();
tokenId = FirebaseInstanceId.getInstance().getToken();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.bottom_nav_view);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
// Intent intent = new Intent(MainActivity.this, AddPostActivity.class);
// startActivity(intent);
fragment = new NotificationsFragment();
break;
case R.id.navigation_post:
fragment = new ProfileFragment();
break;
case R.id.navigation_postlist:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
};
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
protected void onStart()
{
super.onStart();
FirebaseUser currentUser = mauth.getCurrentUser();
if(currentUser == null)
{
SendUserToSignInActivity();
}
else
{
retrieveCurrentUserInfo();
checkUserExistence();
}
}
private void checkUserExistence() {
final String current_user_id = mauth.getCurrentUser().getUid();
}
private void SendUserToSignInActivity() {
Intent signInIntent = new Intent(MainActivity.this, SignInActivity.class);
signInIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(signInIntent);
finish();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = 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;
}
private void retrieveCurrentUserInfo(){
currentUserRef = db.collection("users").document(mUserId);
currentUserRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()){
currentUserName = (String) document.getString("username");
currentUserProfilePic =(String) document.getString("profile_pic");
currentUserSpinnerC = (String) document.getString("spinnerC");
CircleImageView UserImage = (CircleImageView) findViewById(R.id.current_user_Image);
Picasso.get()
.load(currentUserProfilePic)
.resize(50, 50)
.centerCrop()
.into(UserImage);
TextView username = (TextView) findViewById(R.id.current_user_name);
TextView spinnerC = (TextView) findViewById(R.id.current_user_spinnerC);
username.setText(currentUserName);
spinnerC.setText(currentUserSpinnerC);
}
}
}
});
}
}
The fragment is not loaded at launching your activity, so add below code in your onCreate() method
loadFragment(new HomeFragment());
You can trigger the home fragment selection manually. Paste this at the end of the onCreate function of MainActivity.
View view = navigation.findViewById(R.id.navigation_home);
view.performClick();
You are not loading/calling any fragment in your onCreate() method.
Try this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Your code
*/
loadFragment(LOAD_YOUR_FRAGMENT);
}
I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
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);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#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.page__navigation, 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.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}
I have a RecyclerView that launches a new Activity when it is clicked (both long press and short). When I click it the corresponding action is being done 3 times (sometimes 2) in any case it is being done multiple times when I only want it done once. There is a thread that handles these actions but that thread is only executed once.
A quick run thru of the sequence is:
recyclerview is loaded, user can long press or quick click an item on the list.
A quick click calls a openConversation() method which will launch a new activity(in the current version it launches the activity many times because the activity stack has 2-3 instances of the launched activity)
Or if the boolean condition to launch the activity in openConversation() is false a toast message is sent (in this bug the toast is displayed 3 times from my tests)
Like wise on a long press the launched activity is launched 2-3 times when it should only be launched once, because there is more than one instance on the activity stack
public class EventListActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final int VIBRATE_MILLISECONDS = 50;
private static final int REFRESH_ANI_MILLIS = 2500;
final Handler handler = new Handler();
private Context applicationContext;
private List<ParseObject> eventList;
final Runnable updateEventsHard = new Runnable() {
#Override
public void run() {
updateEventCards(true);
}
};
final Runnable updateEventsSoft = new Runnable() {
#Override
public void run() {
updateEventCards(false);
}
};
final Runnable initSwipeRefresh = new Runnable() {
#Override
public void run() {
initSwipeRefresh();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
applicationContext = getApplicationContext();
handler.post(updateEventsHard);
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);
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_event_list);
TextView headerUsername = (TextView) headerLayout.findViewById(R.id.drawer_username);
headerUsername.setText(CurrentActiveUser.getInstance().getUsername());
handler.post(initSwipeRefresh);
}
private void initSwipeRefresh() {
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeView.setColorSchemeResources(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
updateEventCards(true);
swipeView.setRefreshing(false);
}
}, REFRESH_ANI_MILLIS);
}
});
}
#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 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);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case (R.id.nav_my_profile):
Dialog.makeDialog(EventListActivity.this, getString(R.string.upcoming),
getString(R.string.profile_upcoming));
break;
case (R.id.nav_logout):
CurrentActiveUser.getInstance().logout();
Intent intent = new Intent(applicationContext, LoginActivity.class);
startActivity(intent);
finish();
break;
case (R.id.nav_share):
Intent share = new Intent(Intent.ACTION_SEND);
share.setType(StringResources.PLAIN_CONTENT_TYPE);
share.putExtra(Intent.EXTRA_TEXT, R.string.app_share);
startActivity(Intent.createChooser(share, getString(R.string.app_share_title)));
break;
case (R.id.nav_about):
Intent aboutIntent = new Intent(applicationContext, AboutActivity.class);
startActivity(aboutIntent);
break;
case (R.id.nav_legal):
Intent legalIntent = new Intent(applicationContext, LegalActivity.class);
startActivity(legalIntent);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//display clickable a list of all users
#SuppressWarnings("unchecked")
private void updateEventCards(Boolean hard) {
ArrayList<EventObject> eventObjects = new ArrayList<>();
if (NetworkState.isConnected(applicationContext)) {
Query<ParseObject> query = new Query<>(Events.class);
query.orderByASC(Events.START_TIME);
if (hard) {
eventList = query.executeHard();
} else {
eventList = query.execute();
}
ParseObject current;
if (eventList != null) {
if (eventList.size() > 0) {
for (int i = 0; i < eventList.size(); i++) {
current = eventList.get(i);
eventObjects.add(
new EventObject(
current.getString(Events.NAME),
current.getString(Events.LOCATION),
current.getLong(Events.START_TIME),
current.getLong(Events.END_TIME),
current.getString(Events.IMAGE)
)
);
}
} else {
Dialog.makeToast(applicationContext, getString(R.string.no_events));
}
} else {
Dialog.makeToast(applicationContext, getString(R.string.error_loading_events));
}
} else {
Dialog.makeToast(applicationContext, getString(R.string.no_network));
}
attachToEventListAdapter(eventObjects);
}
private void attachToEventListAdapter(ArrayList<EventObject> eventObjects) {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(applicationContext));
eventListClickListener(recyclerView);
EventListAdapter mAdapter = new EventListAdapter(eventObjects, applicationContext);
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
private synchronized void eventListClickListener(RecyclerView recyclerView) {
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(
EventListActivity.this, recyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.d("Click", "Quick");
openConversation(eventList.get(position));
}
#Override
public void onItemLongClick(View view, int position) {
Vibrator vibe = (Vibrator) applicationContext.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(VIBRATE_MILLISECONDS);
openEventInfo(eventList.get(position));
}
}));
}
private void openConversation(ParseObject event) {
Live status = DateVerifier.goLive(event.getLong(Events.START_TIME), event.getLong(Events.END_TIME));
if (status.goLive()) {
Intent intent = new Intent(applicationContext, MessagingActivity.class);
intent.putExtra(IntentKeys.EVENT_ID, event.getObjectId());
intent.putExtra(IntentKeys.EVENT_NAME, event.getString(Events.NAME));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Dialog.makeToast(applicationContext, String.valueOf(System.currentTimeMillis() % 1000));
}
}
private void openEventInfo(ParseObject event) {
Intent intent = new Intent(applicationContext, EventInfoActivity.class);
intent.putExtra(IntentKeys.EVENT_NAME, event.getString(Events.NAME));
intent.putExtra(IntentKeys.EVENT_INFO, event.getString(Events.INFO));
intent.putExtra(IntentKeys.EVENT_CARD, event.getString(Events.MATCH_CARD));
intent.putExtra(IntentKeys.EVENT_IMAGE, event.getString(Events.IMAGE));
intent.putExtra(IntentKeys.EVENT_START_TIME, event.getLong(Events.START_TIME));
intent.putExtra(IntentKeys.EVENT_LOCATION, event.getString(Events.LOCATION));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void onStart(){
super.onStart();
handler.post(updateEventsSoft);
}
public void onResume() {
super.onResume();
handler.post(updateEventsSoft);
}
}
I think your events are being fired 3 times because every time on your RecyclerView you are calling .addOnItemTouchListener() which will add a new listener every time.
Your method eventListClickListener() should only be called once in your onCreate(), not every time in your updateEventsHard() or updateEventsSoft().