can the Fragment be backed to previous fragment? - android

I want to back the default fragment from the other fragment when the back button is clicked but i am not able to back to the previous fragment.How can this be achieved??
EduHunt class main class
public class EduHunt extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
TextView toolBarTitle;
ImageView toolBarLogo;
private Fragment mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_hunt);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolBarLogo = (ImageView) findViewById(R.id.toolbarlogo);
toolBarTitle = (TextView) findViewById(R.id.toolbartitle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.search:
fragmentClass = Search.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Search");
break;
case R.id.settings:
fragmentClass = Settings.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("About");
break;
case R.id.register:
fragmentClass = Register.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Register Now");
break;
case R.id.nearme:
fragmentClass = NearMe.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Near Me");
break;
default:
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.our_team:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.activity_our_team);
dialog.show();
return true;
case R.id.feedback:
startActivity(new Intent(EduHunt.this, SendFeedback.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.education_hunt, menu);
return true;
}
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof Search )){
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
}
}
I want to back to the Search fragment(default fragment) when it is backed from the Any other fragment i.e About
About
public class About extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
LinearLayout collegeAffiliation;
ImageView phoneCalls, sendEmails, weblink;
public TextView aboutName, aboutLocation, aboutNumber, aboutEmail, aboutWebsite, aboutCategory, aboutAffiliation;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_about, container, false);
collegeAffiliation = (LinearLayout) v.findViewById(R.id.collegeAffiliation);
aboutName = (TextView) v.findViewById(R.id.about_school_name);
aboutLocation = (TextView) v.findViewById(R.id.about_school_location);
aboutNumber = (TextView) v.findViewById(R.id.about_school_number);
aboutCategory = (TextView) v.findViewById(R.id.about_school_category);
aboutAffiliation = (TextView) v.findViewById(R.id.about_college_affiliation);
aboutEmail = (TextView) v.findViewById(R.id.about_school_email);
aboutWebsite = (TextView) v.findViewById(R.id.about_school_website);
phoneCalls = (ImageView) v.findViewById(R.id.phonecalls);
sendEmails = (ImageView) v.findViewById(R.id.sendEmails);
weblink = (ImageView) v.findViewById(R.id.weblink);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
aboutName.setText(ourSchool.getSchoolName());
aboutLocation.setText(ourSchool.getSchoolAddress() + "," + ourSchool.getSchoolDistrict() + "," + ourSchool.getSchoolCountry());
aboutNumber.setText(ourSchool.getSchoolPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourSchool.getSchoolType());
aboutEmail.setText(ourSchool.getSchoolEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourSchool.getSchoolWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng schoollatlng = new LatLng(ourSchool.getLatitude(), ourSchool.getLongitude());
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title(ourSchool.getSchoolName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
collegeAffiliation.setVisibility(View.VISIBLE);
aboutName.setText(ourCollege.getCollegeName());
aboutLocation.setText(ourCollege.getCollegeAddress() + "," + ourCollege.getCollegeDistrict() + "," + ourCollege.getCollegeCountry());
aboutNumber.setText(ourCollege.getCollegePhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourCollege.getCollegeType());
aboutAffiliation.setText(ourCollege.getCollegeAffiliation());
aboutEmail.setText(ourCollege.getCollegeEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourCollege.getCollegeWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng collegelatlng = new LatLng(ourCollege.getLatitude(), ourCollege.getLongtitude());
googleMap.addMarker(new MarkerOptions().position(collegelatlng).title(ourCollege.getCollegeName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(collegelatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
aboutName.setText(ourUniversity.getUniversityName());
aboutLocation.setText(ourUniversity.getUniversityAddress() + "," + ourUniversity.getUniversityDistrict() + "," + ourUniversity.getUniverstiyCountry());
aboutNumber.setText(ourUniversity.getUniversityPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourUniversity.getUniversityType());
aboutEmail.setText(ourUniversity.getUniversityEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourUniversity.getUniversityWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng unilatlng = new LatLng(ourUniversity.getUniversityLatitude(), ourUniversity.getUniversityLongitude());
googleMap.addMarker(new MarkerOptions().position(unilatlng).title(ourUniversity.getUniversityName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(unilatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
});
return v;
}
public void callPhoneNumber() {
try {
if (Build.VERSION.SDK_INT > 22) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 101);
return;
}
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
} else {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == 101) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPhoneNumber();
} else {
Log.e("Permission not Granted", "");
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public void sendEmail() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourSchool.getSchoolEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourCollege.getCollegeEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourUniversity.getUniversityEmail(), null));
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
public void setWeblink() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourSchool.getSchoolWebsite()));
startActivity(intent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourCollege.getCollegeWebsite()));
startActivity(intent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourUniversity.getUniversityWebsite()));
startActivity(intent);
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
when i back through the any other fragment .The app closes but i want
to display the default fragment.can this be done???

Check fragment instance in onBackPress event
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof YourDefaultFragment)){
//Load your default fragment
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Set Title");
}
else{
super.onBackPressed();
}
}

you can do it using interface, backstack listner and onBackPress following way
Create BaseFragment
public class FlipkartBaseFragment extends Fragment {
private MainFlipkartActivity activity;
private ChangeCurrentFragment changeCurrentFragment;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (MainFlipkartActivity) getActivity();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof ChangeCurrentFragment)
changeCurrentFragment = (ChangeCurrentFragment) context;
}
#Override
public void onDetach() {
super.onDetach();
changeCurrentFragment=null;
}
public ChangeCurrentFragment onChangeCurrentFragment(){
return changeCurrentFragment;
}
public MainFlipkartActivity getBaseActivity() {
return activity;
}
}
Then extend all fragment using BaseFragment
In fragment you can go one fragment to other like
((MainFlipkartActivity) getBaseActivity()).onFragmentChangeListener(new TwoFKTFragment(),"1"+new Random().nextInt());
Then implement MainActivity like this way
public class MainFlipkartActivity extends AppCompatActivity
implements FragmentManager.OnBackStackChangedListener,ChangeCurrentFragment
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (null == savedInstanceState) {
HomeFragment cameraImportFragment = new HomeFragment();
manageFragment(cameraImportFragment, Const.TAG_HOME);
}
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
}
}
}
public void manageFragment(Fragment fragment, String tag)
{
FragmentManager fragmentManager=getSupportFragmentManager();
// String f_name=fragment.getClass().getName();
if(!fragmentManager.popBackStackImmediate(tag,0))
{
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
}
#Override
public void onFragmentChangeListener(Fragment fragment, String tag) {
manageFragment(fragment,tag);
}
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager=getSupportFragmentManager();
Fragment fr = fragmentManager.findFragmentById(R.id.frame_container);
if(fr!=null){
fr.onResume();
}
}

To Replace fragment if you want back to previous fragment pass addToBackStack=true
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getSupportFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStack();
}
return isPop;
}
put this code in your main activity for backpress
#Override
public void onBackPressed() {
if(!popFragment()) {
super.onBackPressed();
}
}

Related

How to restore fragment states while using bottom navigation view in android?

I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#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 view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.

My application showing blank screen for 2 minutes after login for the first time

In my application for the first time when a user logged in, it is taking 2 min to show the home screen.in that time the screen showing as blank.and it is working fine with oreo version. and application is running fine on emulator also.but when i test with mobile it is showing blank. please help me to resolve it.
public class HomeActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, TabLayout.OnTabSelectedListener {
public static MyAppDataBase myAppDataBase;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
DrawerLayout drawer;
NavigationView navigationView;
ImageView nav_header_profile;
int job_rows_count, policy_row_count;
ImageView img_view_gov_jobs, img_view_my_servant, img_view_gov_policies;
TextView nav_hedaer_user_name, nav_header_mobile;
FloatingActionButton floatingActionButton;
int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
DatabaseReference contactsRef;
UserInfoTable infoTable;
InternetConnection internetConnection;
ContentObserver observer;
String lastTimeStamp;
String previous_timestamp;
List<String> no_of_contacts;
int contactscount;
static UserDetailsAsycTask userDetailsAsycTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*getWindow().setEnterTransition(null);
getWindow().setExitTransition(null);
getWindow().setAllowEnterTransitionOverlap(false);
getWindow().setAllowReturnTransitionOverlap(false);*/
setContentView(R.layout.activity_home);
PreferenceUtils.init(HomeActivity.this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Bharat Next");
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
myAppDataBase = Room.databaseBuilder(HomeActivity.this, MyAppDataBase.class, "userdb")
.addMigrations(MIGRATION_1_2)
.allowMainThreadQueries()
.build();
internetConnection = new InternetConnection(HomeActivity.this);
contactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts");
img_view_gov_jobs = findViewById(R.id.image_view_gov_jobs_for_you);
img_view_my_servant = findViewById(R.id.image_view_my_servant);
img_view_gov_policies = findViewById(R.id.image_view_gov_policies_for_you);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
View header = navigationView.getHeaderView(0);
nav_header_profile = header.findViewById(R.id.nav_header_profile);
nav_hedaer_user_name = header.findViewById(R.id.nav_header_user_name);
nav_header_mobile = header.findViewById(R.id.nav_header_mobile_num);
// userDetailsAsycTask=new UserDetailsAsycTask(HomeActivity.this);
// get();
// infoTable=myAppDataBase.myDao().getUsers();
infoTable=myAppDataBase.myDao().getUsers();
String name = infoTable.getName();
String mobile = infoTable.getMobile_num();
nav_hedaer_user_name.setText(name);
nav_header_mobile.setText(mobile);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
mViewPager = (ViewPager) findViewById(R.id.pager);
// initializeContactUpdatesReceiver();
// getContactTimeStamp(HomeActivity.this);
if (PreferenceUtils.GetLogin()) {
InitializeSession();
}
/* mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);*/
setupViewPager(mViewPager);
// Set up the tabs for ViewPager
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(HomeActivity.this);
drawer = findViewById(R.id.drawer_layout);
img_view_gov_jobs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//govJobs();
if (internetConnection.checkConnection()) {
govJobs();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
img_view_gov_policies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (internetConnection.checkConnection()) {
govPolicies();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
img_view_my_servant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, WorkForActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
// Toast.makeText(HomeActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
}
});
nav_header_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, UserProfile.class));
}
});
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
drawer.setDrawerListener(toggle);
toggle.syncState();
// DialogManager.showProgress(HomeActivity.this);
/*contactsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(infoTable.getMobile_num())){
// DialogManager.hideProgress();
contactsRef.child(infoTable.getMobile_num()).removeValue();
// DialogManager.hideProgress();
CheckContactsFragment();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("test","the error is "+databaseError);
}
});
*/
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogManager.showProgress(HomeActivity.this);
// contactsRef.child(infoTable.getMobile_num()).removeValue();
// CheckContactsFragment();
contactsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(infoTable.getMobile_num())) {
DialogManager.hideProgress();
CheckContactsFragment();
} else if (dataSnapshot.hasChild(infoTable.getMobile_num())) {
contactsRef.child(infoTable.getMobile_num()).removeValue();
DialogManager.hideProgress();
CheckContactsFragment();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("test", "the error is " + databaseError);
}
});
}
});
floatingActionButton.setVisibility(View.VISIBLE);
}
}
});
}
private void CheckContactsFragment() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + mViewPager.getCurrentItem());
// based on the current position you can then cast the page to the correct Fragment class and call some method inside that fragment to reload the data:
if (1 == mViewPager.getCurrentItem() && null != fragment) {
((ContactsFragment) fragment).getContactList(HomeActivity.this);
}
}
private void InitializeSession() {
// DialogManager.showProgress(HomeActivity.this);
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call<SessionResponse> call = apiService.checkToken("Bearer " + PreferenceUtils.GetToken());
call.enqueue(new Callback<SessionResponse>() {
#Override
public void onResponse(Call<SessionResponse> call, Response<SessionResponse> response) {
// DialogManager.hideProgress();
if (response.isSuccessful()) {
if (response.body().getCode() == 201) {
ShowAlert(HomeActivity.this);
} else if (response.body().getCode() == 200) {
Toast.makeText(HomeActivity.this, response.body().getMesg(), Toast.LENGTH_SHORT).show();
} else if (response.body().getCode() == 205) {
ShowAlert(HomeActivity.this);
}
}
}
#Override
public void onFailure(Call<SessionResponse> call, Throwable t) {
// DialogManager.hideProgress();
onError(t);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
menuItem.setChecked(true);
// close drawer when item is tapped
switch (menuItem.getItemId()) {
case R.id.nav_item_jobs:
if (internetConnection.checkConnection()) {
govJobs();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
break;
case R.id.nav_item_policies:
if (internetConnection.checkConnection()) {
govPolicies();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
break;
case R.id.nav_item_my_servant:
// showAlertForm();
// Toast.makeText(HomeActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
startActivity(new Intent(HomeActivity.this, WorkForActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
case R.id.nav_item_about_us:
// Toast.makeText(HomeActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
startActivity(new Intent(HomeActivity.this, AboutUs.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
/* case R.id.nav_item_my_logout:
PreferenceUtils.SaveLogin(false);
PreferenceUtils.saveUserId("");
PreferenceUtils.savePassword("");
DeletedData();
startActivity(new Intent(HomeActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
break;*/
}
drawer.closeDrawers();
return true;
}
public void DeletedData() {
PreferenceUtils.deleteData();
myAppDataBase.myDao().deleteUsers();
myAppDataBase.myDao().deleteUserJobDetails();
myAppDataBase.myDao().deleteUserPolicyDetails();
}
private void govJobs() {
job_rows_count = myAppDataBase.myDao().getNumberOfJobRows();
if (job_rows_count >= 1) {
// getWindow().setExitTransition(null);
Intent intent = new Intent(HomeActivity.this, JobsList.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
} else {
// startActivity(new Intent(HomeActivity.this, JobUserForm.class));
Intent intent =new Intent(HomeActivity.this, JobUserForm.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
}
}
private void govPolicies() {
policy_row_count = myAppDataBase.myDao().getNumberOfPolicyRows();
if (policy_row_count >= 1) {
Intent intent = new Intent(HomeActivity.this, PoliciesGrid.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
} else {
//startActivity(new Intent(HomeActivity.this, PolicyUserForm.class));
Intent intent = new Intent(HomeActivity.this, PolicyUserForm.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/* case R.id.action_sign_out:
PreferenceUtils.SaveLogin(false);
DeletedData();
PreferenceUtils.saveUserId("");
PreferenceUtils.savePassword("");
startActivity(new Intent(HomeActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
break;*/
case R.id.action_contact_us:
startActivity(new Intent(HomeActivity.this, AboutUs.class));
/* Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("text/plain");
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
intent.putExtra(Intent.EXTRA_EMAIL, "bharatnext3444#gmail.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_EMAIL, "bharatnext3444#gmail.com");
startActivity(Intent.createChooser(intent, "Send Email"));*/
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
/* #Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
contactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(infoTable.getMobile_num());
contactsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(dataSnapshot.exists()&&dataSnapshot.hasChildren())){
CheckContactsFragment();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
Toast.makeText(this, "Until you grant the permission, we cannot show contacts of your friends", Toast.LENGTH_SHORT).show();
}
}
}*/
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/* #Override
public void onResume(){
super.onResume();
getContactTimeStamp(HomeActivity.this);
// put your code here...
}*/
}
You tried with other real devices? It's same issue?
This type of error happen when VM heap is Low and in that secession you should increase your ADB emulator Heap to the minimum required.
Into your AVD Manager :
Click Edit on your Emulator
"Show Advanced Settings" at the bottom
Go to: "Memory and Storage"
Edit the VM heap value to 512 MB
Finished

Adding Class Activity to Navigation Drawer Android

Can you tell me how to add class activity into navigation drawer? I am going to create one app where i need to have more than one classes. all of these classes extends activity.I know how to add fragment into navigation drawer but i dont understand how do i add class activity into navigation drawer.
You can add activity for this code....
public class test extends Activity implements View.OnClickListener {
private HeaderBar topActionBar;
private DrawerLayoutAdapter drawerLayoutAdapter;
private DrawerLayout drawerLayout;
private ListView leftDrawer;
private String[] drawerTitle = {"", "Test1", "Test2", "Test3", "Test4", "Test5"};
private int[] drawerIcons = {0,
R.drawable.Test1,
R.drawable.Test2,
R.drawable.Test3,
R.drawable.Test4,
R.drawable.Test5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawerLayoutAdapter = new DrawerLayoutAdapter(test.this, drawerTitle, drawerIcons);
setContentView(R.layout.activity_test);
setId();
setHeaderBar();
changeStatusBarColor();
DrawerLayout.LayoutParams layoutParams = (DrawerLayout.LayoutParams) leftDrawer.getLayoutParams();
leftDrawer.setLayoutParams(layoutParams);
leftDrawer.setAdapter(drawerLayoutAdapter);
if (drawerLayout.isDrawerOpen(leftDrawer)) {
drawerLayout.closeDrawer(leftDrawer);
}
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
});
drawerLayout.closeDrawer(leftDrawer);
displayView(pos);
}
});
}
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(getResources().getColor(R.color.blue));
}
}
private void setId() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
leftDrawer = (ListView) findViewById(R.id.left_drawer);
leftDrawer = (ListView) findViewById(R.id.left_drawer);
}
private void setHeaderBar() {
try {
topActionBar.ivLeft.setVisibility(View.VISIBLE);
topActionBar.ivLeft.setBackgroundResource(R.drawable.menu);
topActionBar.ivLeft.setOnClickListener(this);
topActionBar.tvTitle.setText(R.string.tilte);
} catch (Exception e) {
e.printStackTrace();
}
}
public void openDrawer() {
try {
leftDrawer.invalidateViews();
drawerLayout.openDrawer(leftDrawer);
} catch (Exception e) {
e.printStackTrace();
}
}
private void closeDrawer() {
try {
if (drawerLayout.isDrawerOpen(leftDrawer))
drawerLayout.closeDrawer(leftDrawer);
} catch (Exception e) {
e.printStackTrace();
}
}
private void displayView(final int positionTitle) {
closeDrawer();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (positionTitle) {
case 0:
break;
case 1:
Intent a = new Intent(test.this, act1.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(test.this, act2.class);
startActivity(b);
break;
case 3:
Intent c = new Intent(test.this, act3.class);
startActivity(c);
break;
case 4:
Intent d = new Intent(test.this, act4.class);
startActivity(d);
break;
case 5:
Intent e = new Intent(test.this, act5.class);
startActivity(e);
break;
default:
break;
}
}
}, 200);
}
#Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.ivLeft:
openDrawer();
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

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

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

Android Application - Get last fragment for each activity if already loaded

I actually have an aplication with multiple activitys (on for each icon of my toolbar), also I would like to have the possibility to show the last fragment of these activitys from the stack if the user already open it before.
As you can see in my BaseActivity class below (which I extend for all my activitys), I already add fragments to the stack.
This is my class :
public class BaseActivity extends AppCompatActivity {
private final String TAG = "BaseActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void setImageLoaderConfig(Context context) {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.resetViewBeforeLoading(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
public void initToolBar() {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = (Toolbar) linearLayout.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (toolbar != null) {
initToolbarOnClickListener();
}
}
private void initToolbarOnClickListener() {
(findViewById(R.id.toolbar_relativelayout_news)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ArticlesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_toilettes)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ToilettesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_practice)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(PratiquesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_diary)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(AgendaActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_forum)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ForumActivity.class);
}
});
}
public void updateToolbarIcons(Integer position) {
ImageView imageViewIcon;
Integer[] activeDrawableIds = {R.drawable.menu_actu_hover_320, R.drawable.menu_toilette_hover_320,
R.drawable.menu_pratiques_hover_320, R.drawable.menu_agenda_hover_320, R.drawable.menu_forum_hover_320};
Integer[] inactiveDrawableIds = {R.drawable.menu_actu_160, R.drawable.menu_toilette_320,
R.drawable.menu_pratiques_320, R.drawable.menu_agenda_320, R.drawable.menu_forum_320};
Integer[] imageviewIds = {R.id.toolbar_imageview_news, R.id.toolbar_imageview_bathroom,
R.id.toolbar_imageview_practice, R.id.toolbar_imageview_diary, R.id.toolbar_imageview_forum};
for (int i = 0; i < imageviewIds.length; i++) {
Log.d(TAG, i + " " + imageviewIds[i]);
imageViewIcon = (ImageView) findViewById(imageviewIds[i]);
if (i == position) {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), activeDrawableIds[i]));
} else {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), inactiveDrawableIds[i]));
}
}
if (AfamiciApp.isConnected()) {
ImageView imageViewUser = (ImageView) findViewById(R.id.toolbar_imageview_user);
imageViewUser.setVisibility(View.VISIBLE);
}
}
public void showActivity(Class activityClass) {
Intent intent = new Intent(this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
public void initIsConnected() {
if (AfamiciApp.getMail() != null && AfamiciApp.getPassword() != null) {
AfamiciApp.setIsConnected(true);
}
}
public void showConnexionFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
args.putInt("containerId", layoutId);
ConnexionFragment connexionFragment = new ConnexionFragment();
connexionFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, connexionFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCommentaireFragment(Integer layoutId, Integer id, Boolean isFromConnection) {
if (isFromConnection) {
getSupportFragmentManager().popBackStack();
}
Bundle args = new Bundle();
args.putInt("id", id);
CommentaireFragment commentaireFragment = new CommentaireFragment();
commentaireFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, commentaireFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCompteFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
CreationCompteFragment creationCompteFragment = new CreationCompteFragment();
creationCompteFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, creationCompteFragment, null)
.addToBackStack(null)
.commit();
}
}
Thanks in advance for your replys :)
You can get current fragment(last one added) in the FrameLayout using:
Fragment fragment = getSupportFragmentManager().findFragmentById(layoutId); //layoutId is id of FrameLayout

Categories

Resources