Troubles navigation between fragment - java

I have been investigating for like 4 hours about this problem, but I didnt get any help.
On summary, I am trying to navigate between fragments in Android Studio, using Navigation View. I want to go from Home Fragment to Services Fragment.
The first Home Fragment always load, but when I click on Services item, the fragment Services load, but the data from Home always keeps on the fragment too.
This is my code:
HOME FRAGMENT CLASS
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private PieChart pieChart;
private UserService userService;
private Calendar calendar;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
pieChart = root.findViewById(R.id.pieChart);
userService = UserRepository.getUserService();
getData();
return root;
}
private void getData(){
calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH)+1;
Log.i("INT MONTH", String.valueOf(month));
userService.getHoursPerService(String.valueOf(UserCache.empleado.getId_emp()),String.valueOf(month)).enqueue(new Callback<List<Servicio>>() {
#Override
public void onResponse(Call<List<Servicio>> call, Response<List<Servicio>> response) {
if(response.body().size() == 0){
pieChart.setNoDataText("Sin horas actuales.");
pieChart.setNoDataTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.invalidate();
}else{
List<Servicio> list = response.body();
List<PieEntry> pieEntries = new ArrayList<>();
for(int cont=0;cont<list.size();cont++){
pieEntries.add(new PieEntry(list.get(cont).getTotalHoras(), list.get(cont).getLugarServicio()));
}
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String actual_month = sdf.format(calendar.getTime());
PieDataSet dataSet = new PieDataSet(pieEntries, getResources().getString(R.string.txt_hours_of)+" "+actual_month);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.getDescription().setEnabled(true);
pieChart.getDescription().setText(getResources().getString(R.string.txt_hours_of)+" "+actual_month+".");
pieChart.getDescription().setTextSize(12f);
pieChart.getDescription().setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.99f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleRadius(61f);
pieChart.animateY(2000, Easing.EaseInOutCubic);
pieChart.setEntryLabelColor(ContextCompat.getColor(getContext(),R.color.colorPrimaryDark));
pieChart.setData(data);
pieChart.invalidate();
}
}
#Override
public void onFailure(Call<List<Servicio>> call, Throwable t) {
}
});
}
}
SERVICES FRAGMENT CLASS
public class ServicesFragment extends Fragment {
private ServicesViewModel servicesViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
servicesViewModel = ViewModelProviders.of(this).get(ServicesViewModel.class);
View root = inflater.inflate(R.layout.fragment_myservices, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
servicesViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
MAIN ACTIVITY
public class MainActivityView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private TextView userNameNav;
private TextView userEmailNav;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_view);
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();
}
});*/
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_myservices, R.id.nav_startservice)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(this);
userNameNav = headerView.findViewById(R.id.userNameNav);
userEmailNav = headerView.findViewById(R.id.userEmailNav);
userNameNav.setText(UserCache.empleado.getNombre()+" "+UserCache.empleado.getApellidos());
userEmailNav.setText(UserCache.empleado.getEmail());
navigationView.bringToFront();
}
#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_activity_view, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
AlertDialog.Builder alerta = new AlertDialog.Builder(this);
alerta.setTitle(getResources().getString(R.string.txt_dialog_exit_app));
alerta.setPositiveButton(getResources().getString(R.string.txt_yes_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alerta.setNegativeButton(getResources().getString(R.string.txt_no_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alerta.show();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_home:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,new HomeFragment()).commit();
case R.id.nav_myservices:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new ServicesFragment()).commit();
//NavHostFragment.findNavController(new ServicesFragment());
break;
case R.id.nav_startservice:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new StartServiceFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
onNavigationItemSelected is where I do the navigation.
I tried everything, changing the ConstraintLayout to Relative, insert the fragments from xml into framelayout...
Also, I am using MVVM.
If more information is needed i can post here then.
PD: Sorry if I posting something wrong, this is my first time here.

SOLUTION: I forgot completly to break the first case onNavigationItemSelected.

Related

Attempt to invoke virtual method: has an error java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am getting the following error in my logcat
2020-03-21 16:58:54.611 20322-20322/com.example.bookitup E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bookitup, PID: 20322
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at com.example.bookitup.RecyclerView_Config.setConfig(RecyclerView_Config.java:22)
at com.example.bookitup.MainActivity$2.DataIsLoaded(MainActivity.java:90)
at com.example.bookitup.BookDatabaseEdit$1.onDataChange(BookDatabaseEdit.java:40)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-03-21 16:58:54.622 2004-2019/? W/ActivityTaskManager: Force finishing activity com.example.bookitup/.MainActivity
2020-03-21 16:58:54.622 2004-20389/? I/DropBoxManagerService: add tag=data_app_crash isTagEnabled=true flags=0x2
And here is my code that is causing this NPE of RecyclerView_Config.
public class RecyclerView_Config {
private Context mContext;
private BooksAdapter mBooksAdapter;
public void setConfig(RecyclerView recyclerView, Context context, List<BookActivity> books, List<String> keys){
mContext = context;
mBooksAdapter = new BooksAdapter(books,keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));/*here!!!!!!!!!!!!!!!!!!!!!!!!!*/
recyclerView.setAdapter(mBooksAdapter);
}
class BookItemView extends RecyclerView.ViewHolder {
private TextView mTitle;
private TextView mAuthor;
private TextView mISBN;
private TextView mCategory;
private String key;
public BookItemView(ViewGroup parent){
super(LayoutInflater.from(mContext).inflate(R.layout.book_list_item,parent,false));
mTitle = (TextView) itemView.findViewById(R.id.title_txtView);
mAuthor = (TextView) itemView.findViewById(R.id.author_txtView);
mCategory = (TextView) itemView.findViewById(R.id.category_txtView);
mISBN = (TextView) itemView.findViewById(R.id.isbn_txtView);
}
public void bind(BookActivity book, String key){
mTitle.setText(book.getXbook());
mAuthor.setText(book.getXauthor());
mCategory.setText(book.getXdescription());
mISBN.setText(book.getXisbn());
this.key = key;
}
}
class BooksAdapter extends RecyclerView.Adapter<BookItemView>{
private List<BookActivity> mBookList;
private List<String> mKeys;
public BooksAdapter(List<BookActivity> mBookList, List<String> mKeys) {
this.mBookList = mBookList;
this.mKeys = mKeys;
}
#NonNull
#Override
public BookItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new BookItemView((parent));
}
#Override
public void onBindViewHolder(#NonNull BookItemView holder, int position) {
holder.bind(mBookList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mBookList.size();
}
}
}
Here is the code from my activity
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private RecyclerView mRecyclerView;
//private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme_NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
//setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
Toast.makeText(getApplicationContext(), "on the main page", Toast.LENGTH_LONG).show();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Adding new book, please wait!", Snackbar.LENGTH_LONG).setAction("Action", null).show();
Toast.makeText(getApplicationContext(), "Adding new book, please wait ", Toast.LENGTH_LONG).show();
//progressBar.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, AddBookActivity.class);
startActivity(intent);
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send, R.id.nav_profile_edit)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//piling all books on the main page
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_books);
new BookDatabaseEdit().readBooks(new BookDatabaseEdit.DataStatus() {
#Override
public void DataIsLoaded(List<BookActivity> books, List<String> keys) {
new RecyclerView_Config().setConfig(mRecyclerView,MainActivity.this,books,keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
}
else {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
}
#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) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_logout:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(new Intent(intent));
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
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();
}
}
My BookDatabaseEdit.java
public class BookDatabaseEdit {
private FirebaseDatabase mDatabase;
private DatabaseReference mReferenceBooks;
private List<BookActivity> books = new ArrayList<>();
public interface DataStatus{
void DataIsLoaded(List<BookActivity> books, List<String> keys);
void DataIsInserted();
void DataIsUpdated();
void DataIsDeleted();
}
public BookDatabaseEdit() {
mDatabase = FirebaseDatabase.getInstance();
mReferenceBooks = mDatabase.getReference("Booklist");
}
public void readBooks(final DataStatus dataStatus){
mReferenceBooks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
books.clear();
List<String> keys = new ArrayList<>();
for(DataSnapshot keyNode : dataSnapshot.getChildren()){
keys.add(keyNode.getKey());
BookActivity book = keyNode.getValue(BookActivity.class);
books.add(book);
}
dataStatus.DataIsLoaded(books,keys);
System.out.println(keys);
System.out.println(books);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I think you should implement a getter and setter for Context and use getter to get context with a null check.
So, I fixed this error and my code is working now. The problem was with the RecyclerView_Config.java . The problem was that, basically, my program was trying to populate data from firebase into the app before creating the app.
It is fixed, thanks everyone.

Access a method in fragment method from an activity

I am using an androidx navigation drawer with (fragments), HomeFragment consists of a RecyclerView to show images.
I am trying to call the getMenu() method which updates those images from the MainActivity, but it doesn't work
I have tried to use this MainActivity,but it doesn't work
HomeFragment fragment=new HomeFragment();
fragment.getMenu();
============================HomeFragment================================
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recycler_menu = (RecyclerView)view.findViewById(R.id.recycler_menu);
recycler_menu.setLayoutManager(new GridLayoutManager(context,2));
recycler_menu.setHasFixedSize(true);
mService = Common.getAPI();
getMenu();
return view;
}
public void getMenu() {
compositeDisposable.add(mService.getMenu()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<Category>>() {
#Override
public void accept(List<Category> categories) throws Exception {
displayMenuList(categories);
}
}));
}
private void displayMenuList(List<Category> categories) {
MenuAdapter adapter = new MenuAdapter(context,categories);
recycler_menu.setAdapter(adapter);
}
}
============================MainActivity================================
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu_action_bar ID as a set of Ids because each
// menu_action_bar should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public void onResume() {
super.onResume();
HomeFragment fragment=new HomeFragment();
fragment.getMenu();
}
}
you can't because the method is void and the result is returning back by another method and it's in your fragment.
you should create an interface to pass data from fragment to activity.
HomeFragment:
public class HomeFragment extends Fragment {
private OnAcceptListener listener;
//...
public void getMenu() {
compositeDisposable.add(mService.getMenu()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<Category>>() {
#Override
public void accept(List<Category> categories) throws Exception {
listener.onAccept(categories);
}
}));
}
public void setOnAcceptListener(OnAcceptListener listener) {
this.listener = listener;
}
public interface OnAcceptListener{
void onAccept(List<Category> categories);
}
}
activity:
public class MainActivity extends AppCompatActivity implements HomeFragment.OnAcceptListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
HomeFragment homeFragment = new HomeFragment();
homeFragment.setOnAcceptListener(this);
}
#Override
public void onAccept(List<Category> categories) {
//update here
}
}

Content of ViewPager disappears when navigating back and forth using Navigation Components

After migrating my navigation to the new Jetpack Navigation Component, I found that after navigating back and forth using the the libraries, the content/layout of the first two fragments in my ViewPager disappears. After clicking through the tabs, it comes back though.
At first I thought it was because of the errors that I saw in the logcat, but after fixing them, the problem was still there.
Here is the code of my MainActivity:
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindResources();
// Setup Toolbar & Navigation Component
setSupportActionBar(toolbar);
setupNavigation();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_options, menu);
return super.onCreateOptionsMenu(menu);
}
private void setupNavigation() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph())
.setDrawerLayout(drawerLayout)
.build();
NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
Here is the code of my ViewPagerAdapter:
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
public void addFragment(#NonNull Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
This is my HomeFragment:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindResources(view);
// ViewPager
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPagerAdapter.addFragment(new TodayFragment(), getString(R.string.tab_today_title));
viewPagerAdapter.addFragment(new PriorityFragment(), getString(R.string.tab_priority_title));
viewPagerAdapter.addFragment(new PlannedFragment(), getString(R.string.tab_planned_title));
viewPagerAdapter.addFragment(new TasksFragment(), getString(R.string.tab_tasks_title));
viewPager.setAdapter(viewPagerAdapter);
// TabLayout
tabLayout.setupWithViewPager(viewPager);
}
Java: I fixed the problem by replacing
= new ViewPagerAdapter(getActivity().getSupportFragmentManager());
with
= new ViewPagerAdapter(getChildFragmentManager());
Kotlin: By replacing
= ViewPagerAdapter(fragmentManager)
with
= ViewPagerAdapter(childFragmentManager)

my app running normally but when i am clicking cart button it takes me to first screen from where i started

I am making an online food ordering app.My app was running good but when i add cart code it is showing abnormal behaviour like the cart button takes me to first screen i started.following is the cart.java code
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
FButton btnPlace;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//Firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//Init
recyclerView = (RecyclerView) findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice = (TextView) findViewById(R.id.total);
btnPlace =(FButton)findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
showAlertDialog();
}
});
loadlistfood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One more step!");
alertDialog.setMessage("Enter your Address: ");
final EditText edtAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);//add edt text to alert box
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//submit to firebase
//we will use system.currntMill to key
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank you,Order placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void loadlistfood() {
cart=new Database(this).getCarts();
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
//calculate price
int total=0;
for(Order order:cart)
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale=new Locale("en","US");
NumberFormat fmt=NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
Rest i had put a intent in where cart button is put and else i have cartAdapter class and request.java.If you need them i will edit the question.Please help me.
Here is code that take me to cart.java.
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
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 = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//init firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(getApplicationContext(),Cart.class);
startActivity(cartIntent);
}
});
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);
//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=(RecyclerView)findViewById(R.id.recycler_meu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
adapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(Category.class,R.layout.menu_item,MenuViewHolder.class,category) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
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) {
//Get category id and send to new Activity
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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
// Intent cartIntent = new Intent(Home.this,Cart.class);startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
} else if (id == R.id.log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thank you in advance

Fragment "disappears" after opening new fragment and then coming back

This is kind of hard to explain so I took screenshots of my problem.
So this is my MainActivity.java
I open the navigation drawer and click on Milestones which will bring me to Milestones.java
Here I am at Milestones.java fragment...
working fine for now...
Just how I want it to look.
But when we leave Milestones and go anywhere else and come back it will be messed up. So I will go to Kick Counter.
Here I am in my KickCounter.java fragment
Open navigation drawer and going back to Milestones...
So right now I have fragment Months0Through6 open with Milestones fragment. Some times Months0Through6 and Month12Plus fragments does not show up right away after coming back some times it does. What is always messed up at this point is the Months6Through12 fragment will never display again unless you restart the app. Also swapping between the three fragments is laggy after coming back but never on first view.
Here it is. Where did it go?
youtube video: https://www.youtube.com/watch?v=6yMYcluvqbs
Get Source Here: https://github.com/delaroy/RecyclerViewFragment
I got my code from this youtube video which is almost exactly identical but his MainActivity (which I made into my Milestones fragment) is an activity whereas I used a fragment so I was thinking that might have something to do with my problem.
Milestones.java
public class Milestones extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
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 OnFragmentInteractionListener mListener;
public Milestones() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Milestones.
*/
// TODO: Rename and change types and number of parameters
public static Milestones newInstance(String param1, String param2) {
Milestones fragment = new Milestones();
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);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_milestones, container, false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
//dont know if this will work
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager(), getContext());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for(int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
// Inflate the layout for this fragment
return rootView;
}
// not boiler plate
#Override
public void onResume() {
super.onResume();
}
// probably just adding extra menu dont need it
/*#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
//not boilerplate
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
//not boilerplate
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[]{"0-6 Months", "6-12 Months", "12+ Months"};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Months0Through6();
case 1:
return new Months6Through12();
case 2:
return new Months12Plus();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
return tabTitles[position];
}
public View getTabView(int position){
View tab = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
MilestonesAdapter.java
public class MilestonesAdapter extends RecyclerView.Adapter<MilestonesAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MilestonesAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MilestonesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
Just posting Months0Through6.java because the other two are exactly the same just different strings.
public class Months0Through6 extends android.support.v4.app.Fragment {
public Months0Through6() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MilestonesAdapter adapter = new MilestonesAdapter(new String[]{"Month 0 stuff", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements KickCounter.OnFragmentInteractionListener, MommyMetrics.OnFragmentInteractionListener, Milestones.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener {
Intent shareIntent;
String sharetext = "Hey check out mommy-info here at http://www.mommy-info.com";
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Connects to www.mommy-info.com
myWebView = (WebView)findViewById(R.id.webView_ID);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.mommy-info.com");
myWebView.setWebViewClient(new WebViewClient());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
#Override
public void onBackPressed() {
//back button in navigation drawer logic
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
//back button in webView logic
else if(myWebView.canGoBack()){
myWebView.goBack();
}
else if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.kick_counter_ID) {
KickCounter kickCounter = new KickCounter();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, kickCounter).addToBackStack(null).commit();
} else if (id == R.id.nav_mommy_metrics) {
MommyMetrics mommyMetrics = new MommyMetrics();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, mommyMetrics).addToBackStack(null).commit();
} else if (id == R.id.nav_milestones) {
Milestones milestones = new Milestones();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, milestones).addToBackStack(null).commit();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "my app");
shareIntent.putExtra(Intent.EXTRA_TEXT, sharetext);
startActivity(Intent.createChooser(shareIntent, "share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
In Fragments you need to use getChildFragmentManager(), You are using same Fragment manager in the fragments as in Activity. Hope this will help

Categories

Resources