Changing to Night mode duplicates items in recycler view - java

In my app i have a settings activity to change app to dark mode with SwitchPreference and when there is change in preference app move to MainActivity - parent activity and the MainActivity recyclerView item are duplicated.
SettingsActivity
public class SettingsActivity extends AppCompatActivity {
// same as defined in preference.xml file.
public static final String TAG = "Debug";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
SwitchPreference switchPreferenceCompat = findPreference(getString(R.string.key_dark_mode));
assert switchPreferenceCompat != null;
switchPreferenceCompat.setOnPreferenceChangeListener((preference, newValue) -> {
boolean isChecked = false;
if (newValue instanceof Boolean)
isChecked = (Boolean) newValue;
if (isChecked) {
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_dark_mode), true).apply();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Log.d(TAG, "onCreatePreferences: NIGHT mode on");
} else {
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_dark_mode), false).apply();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d(TAG, "onCreatePreferences: nightmode off");
}
return true;
});
}
}
}
And here is how i read in main activity :
MainActivity
protected void onCreate(Bundle savedInstanceState) {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean switchPref = sharedPref.getBoolean(getString(R.string.key_dark_mode), false);
//Toast.makeText(this, Boolean.toString(switchPref), Toast.LENGTH_SHORT).show();
if (switchPref) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//setTheme(R.style.NightMode);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
//setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
I even tried MainActivity without PreferenceManager still items in recyclerView are duplicated.

Related

How to close Unity without closing the entire app when changing fragments in Android Studio?

I have an app that the user can go through different fragments using BottomNavigationView and one of those fragments is a Unity3D application. So when i open the Unity fragment it works but when i open another fragment and open the Unity fragment back it crashes how do i fix this here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView mBottomNavigationView;
NavController mNavController;
NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
private boolean doubleBackToExitPressedOnce ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_SHORT).show();
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
//Toast.makeText(getApplicationContext(), mDestination.toString(),Toast.LENGTH_SHORT).show();
if (doubleBackToExitPressedOnce) {
getSupportFragmentManager().popBackStackImmediate();
mNavController.navigate(mDestination.getId());
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
UnityMapFragment
public class MapFragment extends Fragment{
protected UnityPlayer mUnityPlayer;
FrameLayout frameLayoutForUnity;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mUnityPlayer = new UnityPlayer(getActivity());
View view = inflater.inflate(R.layout.fragment_map, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.frameLayoutForUnity);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
#Override
public void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override
public void onResume() {
super.onResume();
mUnityPlayer.resume();
}
// Quit Unity
#Override
public void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
So I managed to make a solution for this problem don't know if its good to make it this way or not but what i did was I instantiate the UnityPlayer in my MainActivity and in my fragment i call upon the UnityPlayer that was instatiated in my Main Activity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public BottomNavigationView mBottomNavigationView;
public NavController mNavController;
public NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
int onBackTimes = 0;
public UnityPlayer mUnityPlayer; <----Call unity player
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(this); <----UNITY PLAYER HERE
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
onBackTimes +=1;
if(onBackTimes>1){
LoginActivity.close.finish();
finish();
}
else{
getSupportFragmentManager().popBackStackImmediate();
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
mNavController.navigate(mDestination.getId());
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onBackTimes=0;
}
}, 2000);
}
#Override
protected void onStop() {
super.onStop();
}
//UNITY STUFF OVER HERE
#Override
protected void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
}
UnityMapFragment
public class MapFragment extends Fragment{
private MainActivity mUnityMainActivity;
private UnityPlayer mUnityPlayer;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this code calls the UNITYPLAYER from MainActivity and return it here
mUnityMainActivity = (MainActivity) getActivity();
View unityPlayViewer = mUnityMainActivity.mUnityPlayer.getView();
mUnityMainActivity.mUnityPlayer.requestFocus();
mUnityMainActivity.mUnityPlayer.windowFocusChanged(true);
return unityPlayViewer;
}
/** FOR UNITY **/
#Override
public void onPause() {
super.onPause();
mUnityMainActivity.mUnityPlayer.pause();
}
// Resume Unity
#Override public void onResume()
{
super.onResume();
mUnityMainActivity.mUnityPlayer.resume();
}
I don't know why i have to include the OnPause, OnResume etc on both file but if one of them doesn't have it it'll crash.
The problem is, a new UnityPlayer is being created every-time we switch to the unity fragment and this crashes the app. So we need to create the UnityPlayer only for the first time or only when the player has been stopped. This works on my side.
In the UnityFragment class, my global variables :
protected UnityPlayer mUnityPlayer;
private View view;
private FrameLayout frameLayoutForUnity;
In onCreate a new UnityPlayer is created, which is called only for the first time :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(getActivity()); // create Unity Player
}
In onCreateView we refresh the view for UnityPlayer :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(mUnityPlayer.getParent() != null){
((ViewGroup)mUnityPlayer.getParent()).removeAllViews();
}
view = inflater.inflate(R.layout.fragment_unity, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.unityFragmentLayout);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
Rest remains same. There could be better solutions than this. Cheers :)

Save and retrieve v4 Fragment state

I've read countless topics regarding saving and retrieving the state of Fragments by now. Unfortunately nothing has worked for me and Bundle savedInstanceState is always returning null. What i wanna do is implement a "shopping cart" which remembers the items the user selected. To make that possible I just want to save one variable of the Fragment and retrieve it once the Fragment is called again.
Not only do I want to make the fragment retain it's state when called from the backstack, but also when opening it from the BottomNavigationView. Or does it even make any difference?
Here is the parent Activity class of all the Fragments:
public class ShopMainViewScreen extends AppCompatActivity implements ShopFragment.OnFragmentInteractionListener, SearchFragment.OnFragmentInteractionListener, ... {
Fragment mContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
loadFragment(new ShopFragment());
mContent = getSupportFragmentManager().findFragmentById(R.id.fragmentplace);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new ShopFragment();
loadFragment(fragment);
return true;
case R.id.navigation_search:
fragment = new SearchFragment();
loadFragment(fragment);
return true;
case R.id.navigation_shoppingCart:
fragment = new CartFragment();
loadFragment(fragment);
return true;
case R.id.navigation_settings:
fragment = new SettingsFragment();
loadFragment(fragment);
return true;
}
return false;
}
};
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentplace, fragment)
.addToBackStack(null)
.commit();
}
return false;
}
This is the Fragment containing the variable (mShoppingCart which ought to be stored and retrieved).
public class CartFragment extends Fragment {
private String mTitle;
private int mQuantity;
ArrayList < String > mShoppingCart;
private OnFragmentInteractionListener mListener;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.i("onSaveInstanceState", "entered");
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putStringArrayList("CART", mShoppingCart);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Log.i("onActivityCreated", "entered");
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
Log.i("SavedInstanceState", " not null");
mShoppingCart = savedInstanceState.getStringArrayList("CART");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("onCreate", "entered");
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString("PRODUCTTITLE");
mQuantity = getArguments().getInt("QUANTITY");
}
if (savedInstanceState == null) {
Log.i("InstanceState", "is null");
mShoppingCart = new ArrayList < > ();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
validateCart(mTitle, mQuantity);
return inflater.inflate(R.layout.shoppingcart_fragment_layout, container, false);
}
#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;
}
Any help is appreciated.
savedInstanceState is only hydrated during configuration changes or when the app is backgrounded & brought back to the foreground. To save the state of a shopping cart throughout a user's session consider using a view model attached to the parent activity. You could also try persisting the cart in SQLite if you'd like that data to be retained across multiple sessions.

How do I get my theme to programmatically get carried over into other activities?

I've created a function in the settings page of my app which contains a switch - that when pressed - switches to a secondary "Night" theme. I followed this tutorial for the most part. However, I don't know how to carry this night mode into my other activities? I've tried calling the "if switch checked" in my main activity, but it obviously doesn't see that switch. What I mainly need to know is, how do I check a switch state in another activity? And is this even the right way of doing it? Let me know if I've missed anything else in this question.
// ======== CODE FOR THE SETTINGS PAGE ======== //
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// ======== Night Mode ======== //
SwitchCompat switchCompat;
final SharedPref sharedPref;
sharedPref = new SharedPref(this);
if (sharedPref.loadNightModeState()) {
setTheme(R.style.AppTheme_Night);
getSupportActionBar().setBackgroundDrawable(getDrawable(R.drawable.actionbar));
actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.BackgroundLight));
} else setTheme(R.style.AppTheme);
setContentView(R.layout.activity_settings);
switchCompat = (SwitchCompat) findViewById(R.id.night_switch);
if (sharedPref.loadNightModeState()) {
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
sharedPref.setNightModeState(true);
restartApp();
} else {
sharedPref.setNightModeState(false);
restartApp();
}
}
});
}
private void restartApp() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
finish();
}
// ======== SharedPref CODE ======== //
public class SharedPref {
private SharedPreferences sharedPreferences;
public SharedPref(Context context) {
sharedPreferences = context.getSharedPreferences("filename", Context.MODE_PRIVATE);
}
public void setNightModeState(Boolean state) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode",state);
editor.apply();
}
public Boolean loadNightModeState (){
Boolean state = sharedPreferences.getBoolean("NightMode", false);
return state;
}
In you application class inside onCreate
SharedPreferences sharedPreferences = getSharedPreferences("Your_Shared_pref", Context.MODE_PRIVATE);
boolean nightMode = sharedPreferences.getBoolean(SettingsActivity.DARK_THEME_PREFERENCE_KEY, false);
AppCompatDelegate.setDefaultNightMode(nightMode ? MODE_NIGHT_YES : MODE_NIGHT_NO);
Than in your activity, do this:
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
AppCompatDelegate.setDefaultNightMode(isChecked ? MODE_NIGHT_YES : MODE_NIGHT_NO);
if (isChecked) {
sharedPref.setNightModeState(true);
recreate();
} else {
sharedPref.setNightModeState(false);
recreate();
}
}
});
#Override
public void recreate() {
finish();
overridePendingTransition(R.anim.anime_fade_in,
R.anim.anime_fade_out);
startActivity(getIntent());
overridePendingTransition(R.anim.anime_fade_in,
R.anim.anime_fade_out);
}
you can find the animation xml online.
I put this between my onCreate and my super.onCreate. The code I used was taken from my settings java page. It turns out that it was pretty easy to figure, I just needed someone to put it into perspective!
#Override
protected void onCreate(Bundle savedInstanceState) {
final SharedPref sharedPref;
sharedPref = new SharedPref(this);
if (sharedPref.loadNightModeState()) {
setTheme(R.style.AppTheme_Night);
//restartApp();
//getSupportActionBar().setBackgroundDrawable(getDrawable(R.drawable.actionbar));
//actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.BackgroundLight));
} else setTheme(R.style.AppTheme);
//restartApp();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Autocomplete search bar using Google Places API in a fragment

My app currently looks like this:
I want to add a search bar where I can search any place as Google maps. The search bar should be in an Auto Complete way.I got this code from https://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/
Have a look at the above link.
And these codes where for an ORDINARY APP to get Auto Complete search bar. It doesnt suit for app using fragment. And I dont know how to do it with fragments.
Here is my code
For the Main Activity (ProfileActivity)
public class ProfileActivity extends AppCompatActivity {
final String TAG = this.getClass().getName();
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.menu_user, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int i) {
if(i == R.id.ButtonBarFeed)
{
NewsFragment f = new NewsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarMap)
{
MapFragment f = new MapFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarUser)
{
UserFragment f = new UserFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
}
});
mBottomBar.mapColorForTab(0,"#28809f");
}
public boolean googleServicesAvailable(){
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(api.isUserResolvableError(isAvailable)){
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this,"Can't connet to Play Services", Toast.LENGTH_LONG).show();
}
return false;
}
boolean twice;
#Override
public void onBackPressed() {
Log.d(TAG, "click");
if(twice == true){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice:" + twice);
Toast.makeText(ProfileActivity.this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice:" + twice);
}
}, 3000);
}
}
MapFragment
public class MapFragment extends Fragment implements OnMapReadyCallback {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment fragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.mapView1);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap){
}
}
I have to add a search bar with Auto Complete like Google map.Please with reference of the Link which I have given at starting, Can Anyone code for my MapFragment?

android using getchildFragmentManager to retain fragments when replase and reding

I have implement an app that has a fragment system exactly like Instagram.
When I select a tab in bottom tab the fragment is replaced in the container.
My problem is when I go to another fragment and get back to this fragment the data is reloading and the fragment recreating.
I have searched and no answer helped me. I see this answer and I think it's correct, but I don't know how to use it and what FragmentMetaData is.
This is my main activity:
public class MainActivity extends FragmentActivity {
//set this tablayout to puplic static, so we can access this from othere fragment
public static TabLayout tabLayout_bottom;
Fragment fragmentHome = new FragmentHome();
Fragment fragmentSearch = new FragmentSearch();
Fragment fragmentLikes = new FragmentLikes();
Fragment fragmentProfile = new FragmentProfile();
//use fragment manager to manage fragment
private FragmentManager fragmentManager = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set current fragment to FragmentHome when activity start
this.getSupportFragmentManager().beginTransaction().replace(R.id.container, fragmentHome).commit();
tabLayout_bottom = (TabLayout) findViewById(R.id.tabs_bottom_home);
//this code change color of statusbar if current android version is more then lollipop
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
createTabIcons_bottom();
//this method change the language of hole app. so if user change his device language, the app not changing
//if you want persian change "en" to "fa"
String languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
}
private void createTabIcons_bottom() {
//this set icon for each tab
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_home_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_search_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_add_box_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_favorite_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_person_black_24dp));
//set color for each icon
tabLayout_bottom.getTabAt(0).getIcon().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(1).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(2).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(3).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(4).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//set color when tab selected
int tabIconColor = ContextCompat.getColor(getApplicationContext(), R.color.colorAccent);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
if (tab.getPosition() == 0) {
GotoFragmentHome();
}
else if (tab.getPosition() == 1) {
GotoFragmentSearch();
}
else if (tab.getPosition() == 2) {
GotoActivityAdd();
}
else if (tab.getPosition() == 3) {
GotoFragmetnLikes();
}
else if (tab.getPosition() == 4) {
GotoFragmetnProfile();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//set color if tab unselect
int tabIconColor = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//each method is for a fragment that use when a tab seleted
//the addToBackStack method hold that fragment in a stack so when back pressed, geting back to last fragment
public void GotoFragmentHome() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentHome).addToBackStack("home").commit();
}
public void GotoFragmentSearch() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentSearch).addToBackStack("search").commit();
}
public void GotoActivityAdd() {
startActivity(new Intent(getApplicationContext(), ActivityAdd.class));
}
public void GotoFragmetnLikes() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentLikes).addToBackStack("likes").commit();
}
public void GotoFragmetnProfile() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentProfile).addToBackStack("profile").commit();
}
#Override
public void onBackPressed() {
//this says that if no fragment was in stack, so exit app
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else {
//exit hole app
moveTaskToBack(true);
return;
}
}
}
And this is one of my fragments:
public class FragmentSearch extends Fragment {
private LinearLayout toolbar_search;
public FragmentSearch() {
// Required empty public constructor
}
View rootView;
#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
rootView = inflater.inflate(R.layout.fragment_search, container, false);
//select search tab if user back to this fragment
MainActivity.tabLayout_bottom.getTabAt(1).select();
//save current tab position in sharedpreferance. so if uer get back from Add Activity, select last tab
int tabselected=MainActivity.tabLayout_bottom.getSelectedTabPosition();
SharedPreferences.Editor editor=getActivity().getSharedPreferences("selectedtab", Context.MODE_PRIVATE).edit();
editor.putInt("selectedtab",tabselected);
editor.commit();
toolbar_search=(LinearLayout) rootView.findViewById(R.id.toolbar_in_searchfragment);
toolbar_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), ActivitySearch.class));
}
});
return rootView;
}
}
If somebody help me I'd be grateful. I see the savedInstanceState in some answers but that has not worked for me.

Categories