How to refesh fragment when delete data from DB - java

i have below code for data remove from DB.
So i delete data but i want to update fragment from here.
how i can refesh fragment ?
// Remove entry from database table
database.delete(FAVORITES_TABLE, FAVORITES_ITEM_ID + " = " + soundObject.getItemID(), null);
// Refesh current fragment
????????????????????????????????
this is code which i use in Fragment to refesh it (on button press) work good, but i don't want to tap refesh button to refesh page. I want fragment refesh when DB change by it self.
public void refersh()
{
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
}
any idea?
Thanks

you are detaching and attaching again in one commit, so it does nothing. make it two commits
public void refersh(){
FragmentTransaction ft1 = getFragmentManager().beginTransaction();
ft1.detach(this).commit();
FragmentTransaction ft2 = getFragmentManager().beginTransaction();
ft2.attach(this).commit();
}
there is also possibility that you shoud use getSupportFragmentManager instead of getFragmentManager
its probably not best/most-efficient solution, but you posted ony this small snippet...

In simple terms you can use:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();

I think you want to refresh the fragment contents upon DB data updates
If so, detach the fragment and again attach it
// Reload current fragment
Fragment f1 = null;
f1 = getSupportFragmentManager().findFragmentByTag("Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(f1);
ft.attach(frg);
ft.commit();
Fragment_TAG is the name you gave your fragment when you created it

To refresh the current fragment content, you can use the following code inside the method refresh()
public void refresh()
{
Fragment fragment = null;
fragment = new Current_Fragment_Name(); //replace the Current_Fragment_Name with your current fragment name
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
Hope it works for you.

Related

Return to a fragment already created

I'm working on an Android application that uses fragments.
The code is supposed to do the following:
I'm in the mainActivity;
In here there's a button that creates a fragment;
Turn on an on/off button;
I go back to the mainActivity;
I click on the button and go to the created fragment;
The on/off button is turned on;
I tried to implement this and it doesn't work. In step 5 I believe that it's creating a new fragment everytime, because the on/off button is always turned off.
Basically want I want is to go back to the same fragment that I created firstly.
This is the current code that I have:
MainActivity:
public void onStartSensors(View view) {
if(count > 0){
getSupportFragmentManager().popBackStack();
}
else{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.container, new StartupFragment());
transaction.addToBackStack(null);
transaction.commit();
count++;
}
}
UPDATE:
In the link bellow, I got a representation of the present state of my application. When I enter the fragment for the second time, I want it to keep the accelerometer ON.
https://ibb.co/Sc7QZDt
I already tried the method popBackStack(), added a tag, name etc. and it doesn't work.
When I get out of the fragment the method getFragmentByTag() returns null.
This is the current state of the code:
public void onStartSensors(View view) {
FragmentManager fm = getSupportFragmentManager();
if(count > 0){
StartupFragment f1= (StartupFragment) fm.findFragmentByTag("A");
FragmentTransaction transaction=fm.beginTransaction();
if( f1 != null) {
transaction.attach(f1);
transaction.addToBackStack("sensors");
transaction.commit();
}
}
else{
StartupFragment f1=new StartupFragment();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.container, f1, "A");
transaction.addToBackStack("sensors");
transaction.commit();
count++;
}
}
It seems to me that you want to add a fragment to be displayed on top of the current activity that is able to be hidden and shown on demand. Looking at your code, every time you are 'showing' the fragment you are creating a new StartupFragment so the behaviour you are experiencing makes sense.
So I would instead recommend adding the fragment when the activity starts and then using FragmentTransaction.show(Fragment) and FragmentTransaction.hide(Fragment) to toggle it's visibility.

Replace a Fragment with another from a separate java class

I have a Recycler View in a Fragment that I have an adapter class for in a separate file. I am trying to make it so that when you click on a RecyclerView Item it replaces the current fragment with a new one. The code to replace a fragment with another that I had been using previously is this:
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.nav_host_fragment, NewFragment.class, null);
transaction.addToBackStack("CurrentFragment");
transaction.commit();
And this works inside the fragment, but since I have to call it from the java class I tried this instead:
FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.nav_host_fragment, NewFragment.class, null);
transaction.addToBackStack("CurrentFragment");
transaction.commit();
And this just layers the new fragment on top of the current one. If I try making a class in the Current Fragment with the transaction code in it and call it, it doesn't work because of the static context.
Is there any way to do this?

Completely Refresh Fragment

I have a fragment and I need to completely refresh/reinstantiate it.
By refreshing I mean recreating fragment.
I have tried using FragmentManager with detach() method but it didn't help. All EditText children of that fragment still have their values entered even though the fragment was refreshed
Is there any way to achieve this result?
if there are only edit texts , create a method that sets all edit texts to empty string that is et(edit_text object),
et.setText(""); //edit text will be reset
Put the following code inside the fragment which need to be refreshed.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
Use fragment manger according to your code (if it is an old version then this will be supportFragmentManager)
Put and call this method to your fragment
private void reloadFragment(){
Fragment frg = getActivity().getSupportFragmentManager().findFragmentByTag(ReceiptFragment.TAG);
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}

Calling Fragment Method from Activity in Swipeable Tab Views

I've been working on a project that has swipeable views with tabs.
The tabs exist as fragments. I want to run a fragment method from the main activity on a periodic basis.
To run the methos, I dont' have the ID for the fragment. I read in other posts that:
String tag = "android:switcher:" + TabActivity.this.viewPager.getId() + ":" + "0";
Tab1Fragment fragment = (Tab1Fragment) getSupportFragmentManager().findFragmentByTag(tag);
fragment.someMethod();
will return the fragment I desire, which happens to be the zero-th or first tab. However, running this code returns a nullpointer exception.
Any help will be appreciated. Thanks :)
In your code, at some point you must have:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.framelayout, new SomeXYZFragment(), "some_xyz_fragment");
ft.commit();
Add the line:
fm.executePendingTransactions();
after the line ft.commit();
Try this. It should work.

Replacing a fragment with another fragment inside activity group

I have a fragment inside a group activity and I want to replace it with another fragment:
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
It works fine when it is done as a seperate project without using activity group, every thing works fine in log cat as control goes inside getview(), but no view is visible, not even any exception arises, I want the book detail fragment to be replaced by section detail fragment.
Xml of book detail fragment has id book_description_fragment and xml for section description fragment has id section_description_fragment.
The above code is in onClick method of an item, I want that when user taps on an item in horizontal scroll view, then the fragment changes.
Fragments that are hard coded in XML, cannot be replaced. If you need to replace a fragment with another, you should have added them dynamically, first of all.
Note: R.id.fragment_container is a layout or container of your choice in the activity you are bringing the fragment to.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Please see this Question
You can only replace a "dynamically added fragment".
So, if you want to add a dynamic fragment, see this example.
I've made a gist with THE perfect method to manage fragment replacement and lifecycle.
It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).
It contain several option as if you want the fragment to be saved in backstack.
=> See Gist here
Using this and a single Activity, you may want to add this to your activity:
#Override
public void onBackPressed() {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
return;
}
super.onBackPressed();
}
Use the below code in android.support.v4
FragmentTransaction ft1 = getFragmentManager().beginTransaction();
WebViewFragment w1 = new WebViewFragment();
w1.init(linkData.getLink());
ft1.addToBackStack(linkData.getName());
ft1.replace(R.id.listFragment, w1);
ft1.commit();
Use ViewPager. It's work for me.
final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager);
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(1);
}
});
hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about
1- How to switch fragment with other.
2- How to add fragment if Fragment container does not have any fragment.
then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.
public void switchFragment(BaseFragment baseFragment) {
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
ft.add(R.id.home_frame, baseFragment);
} else {
ft.replace(R.id.home_frame, baseFragment);
}
ft.addToBackStack(null);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
enjoy your code time :)
you can use simple code its work for transaction
Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit();
You Can Use This code
((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();
or You Can This Use Code
YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);
if (fragments==null) {
getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
}
I change fragment dynamically in single line code
It is work in any SDK version and androidx
I use navigation as BottomNavigationView
BottomNavigationView btn_nav;
FragmentFirst fragmentFirst;
FragmentSecond fragmentSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
fragmentFirst = new FragmentFirst();
fragmentSecond = new FragmentSecond ();
changeFragment(fragmentFirst); // at first time load the fragmentFirst
btn_nav = findViewById(R.id.bottomNav);
btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.menu_first_frag:
changeFragment(fragmentFirst); // change fragmentFirst
break;
case R.id.menu_second_frag:
changeFragment(fragmentSecond); // change fragmentSecond
break;
default:
Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
public void changeFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
}
In kotlin you can do:
// instantiate the new fragment
val fragment: Fragment = ExampleFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()
This will work if you're trying to change the fragment from another fragment.
Objects.requireNonNull(getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment_container,new NewFragment())
NOTE As stated in the above answers, You need to have dynamic fragments.
You can use fragment-ktx
// If you are in fragmet
childFragmentManager.beginTransaction()
// or if you are in activiry
supportFragmentManager.beginTransaction()
// Create and commit a new transaction
supportFragmentManager.commit {
setReorderingAllowed(true)
// Replace whatever is in the fragment_container view with this fragment
replace<ExampleFragment>(R.id.fragment_container)
}
To replace a fragment with another one do this, Note that R.id.fragment comes from the id that you give to the first tag of the fragment in the XML.
barAudioPlaying.setOnClickListener(view -> {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment,new HomeFragment())
.commit();

Categories