Reputation: 56
So I've recently got into Android programming and for a while I've been struggling with this problem. I use navigation drawer and got some fragments attached to it. But whenever I switch tabs/fragments, all variables are reset and I have to manually reset them again.
However, I would like if it were automatical. After fragment load -> refresh data from custom class..
This is my code of the fragment, but it crashes on nullpointerexception.
public class TimeFragment extends Fragment {
private final String ARG_SECTION_NUMBER = "section_number";
public TimeFragment(int sectionNumber) {
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
this.setArguments(args);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_time, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
refreshFragment();
}
public void refreshFragment() {
TextView text_first = (TextView) findViewById(R.id.textViewNS_Days);
TextView text_second = (TextView) findViewById(R.id.textViewNS_Money);
TextView text_third = (TextView) findViewById(R.id.textViewNS_Cigs);
text_first.setText(String.format("%d", smokes.daysNotSmoked()));
text_second.setText(String.format("%.1f", smokes.moneySaved()));
text_third.setText(String.format("%d", smokes.cigsNotSmoked()));
}
}
and this is the default method that sets up fragments.
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = new PlaceholderFragment(position + 1);
switch (position) {
case 0:
fragment = new TimeFragment(position + 1);
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Upvotes: 0
Views: 773
Reputation: 56
I found out I can use
@Override
public void onResume(){
}
on fragments. Solved it.
Upvotes: 1