How to refresh all activity from one activity - java

I have multiple fragments with its activity.
When I refresh in MainActivity, I want all fragment's activity to refresh as well. Because I work with database and it involves refreshing others fragments to update the data.
MainActivity.kt
swipeRefresh.setOnRefreshListener {
// refreshing MainActivity only
// I don't know how to call fragment's activity here
swipeRefresh.isRefreshing = false
}

Fragment is dependent on activity and activity is not dependent on fragment. What you do in activity will affect the fragment. Do use this a starting point to look up.

In the activity, you can call recreate() to "recreate" the activity (API 11+)
or you can use this for refreshing an Activity from within itself.
finish();
startActivity(getIntent());

Related

How to get onNewIntent() in a Navigation Fragment

I want to use Navigation component in my android project, in order to achieve this, I have refactored my app to be fragment-based, but it raises a problem that I don't know how to pass onNewIntent() in my MainActivity to my Navigation Fragments.
So MainActivity is a NavHost, to make it simple, saying that I have a fragment as the start destination, how can I get onNewIntent() inside this fragment from MainActivity?
UPDATE
Also, is there a way to get the reference of the current presented fragment, like the one currently held by NavHost?
On new intent , you can do something like
val navigationController = nav_host_fragment.findNavController()
if (navigationController.currentDestination?.id == R.id.fragmentA) {
(nav_host_fragment.childFragmentManager.fragments[0] as FragmentA).doSomething()
}
Here you can pass any values to the function doSomething()
You can use in MainAcitivy class this:
private Fragment fragment;
fragment = new FragmentTry();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentid, fragment)
.commit();

What is the best way to maintain the backstack of my Activity after Activity.Recreate() is called?

I have an Activity that handles many Fragments, and, for backstack management, I have a custom stack, where I manage show / hide for Fragments. My code and navigation work perfectly.
Right now, I am implementing the application theme change by a Button in the Configuration Fragment. For this I am using the method Activity.Recreate (); for the change of the theme and, the data of the Configuration Fragment is retained with the same data and the theme of the application changes perfectly, but the BackStack of Fragments disappears, reason why, when pressing the back button, it leaves the application, instead of sending me back to the Fragment or Previous Activity, from where I accessed the Configuration Fragment.
What is the best way to maintain the backstack of my Activity? This is possible?
Important: only when Activity.Recreate(); is called, because if the Activity is destroyed by any other way, I do not want the BackStack back, I want my Activity clean.
Additional:
The orientation setting of my application is in portrait mode.
The launchMode of my Activity is singleTask, it must be so for the type of application I am doing.
From onCreate documentation and this answer.
Add the following logic to your code:
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) {
// savedInstanceState will be null only when creating the activity for the first time
backstack = new BackStack(); //init your backstack
} else {
// there is a chance that your backstack will be already exists at this point
// if not:
// retrieve the backstack with savedInstanceState.getSerializable("stack")
}
}
And just clear the stack when changing theme, before calling recreate()
// changing theme detected
bacstack.clear();
backstack = null;
recreate();
To save the stack between destruction (onDestroy) and recreation (onCreate) of your activity, Use this method:
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (backstack != null) // the check isn't necessary, you can just put a null in the bundle
outState.putSerializable("stack", backstack);
}
the official guide
for saving UI state
The onSaveInstanceState method helps your activity to Survive
Configuration change and System-initiated process death.
link

How to close all open Activities and open a new one from a Java Class

I have created a class that is extending from CountDownTimer, It has a a method onFinish() which calls when timer expires.
There are 6 Activities, user can be in any activity when timer expires, So in CounterTimerwhen Finish() method calls , i need to show an Alert Message to the user,along with i need to redirect user to Login page.
Things getting confusing, as i cannot call Intent class in the Normal Class, I can also not pass the context, as user can be in any activity.
I have written following code, but its not helping out.
I am using context here, but its giving error message on passing context to Intent
public class CounterClass extends CountDownTimer implements ITMServiceEvent {
#Override
public void onFinish() {
if(sql_code.equalsIgnoreCase("0")) {
String resultCode = command1.getString("result");
context.startActivity(context.getApplicationContext(), MainActivity.class);
}
Calling Timer at the Start of Wizard, in a Fragment
CounterClass counterClass= new CounterClass(180000,1000);
counterClass.setTextView(tvTimer);
counterClass.start();
There are two parts of your question, first is how you can clean up the Activity stack and start a new Activity on Top of them, I suppose this would be the LoginActivity in your case.
To do this, you need to set the Flag of your LoginActivity Intent when you want to start it,
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
And the second part is, you want to be able to finish the current activity after showing a dialog to the user. I assume your Timer is a Service Class, which runs in the background. The way to tell your current activity that the Time is Up ! is to send a Broadcast Message. Preferably, LocalBroadcastManager can help you out. You can have a BaseActivity class where all of your 6 Activities can be extended from it and you can register/unregister LocalBroadcastManager to/from those activities in the BaseActivity class (register in onResume and unregister in onPause). After you register them you just need to implement and handle the onReceive method where you can show a dialog and start the LoginActivity after finishing the current one.

Force My Activity To Call The onSavedInstance State

I have an android application in which I use two themes. On theme change I need to recreate all the activities and Fragments inside that to be recreated.
The same way our application get recreated using saved instnce state.
Is there any way I can force my Activity to call the saved instance state ? IF it is possible how I can do that ? If not why ? Is there any alternative to Achieve this ?
My current code looks like below.
public static final void restartActivity(final FragmentActivity activity){
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
The issue with this is the fragment back stack is not getting recreated. Any help would be greatly appreciated.
Your state is not saved because you're creating a new instance of Activity. As a solution, you can pass your state to this new instance as Intent extras and restore state in onCreate from those extras.

Android: how can fragment take a global variable of Activity

I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?
Either set the var as public static, or use
((MyActivity)getActivity()).getX()
Using a public static variable isn't the best way to communicate between an activity and a fragment. Check out this answer for other ways:
The Android documentation recommends using an interface when the Fragment wants communicate with the Activity. And when the Activity wants to communicate with the Fragment, the Activity should get a reference to the Fragment (with findFragmentById) and then call the Fragment's public method.
The reason for this is so that fragments are decoupled from the activity they are in. They can be reused in any activity. If you directly access a parent Activity or one of its global variables from within a fragment, you are no longer able to use that fragment in a different Activity.
Kotlin version:
(activity as MyActivity).x
***In your Activity
==================
Bundle args = new Bundle();
args.putInt("something", Whatever you want to pass);
fragA.setArguments(args);
In your Fragment
==================
Bundle args = getArguments();
//whatever you want to get ,get it here.
//for example integer given
int index = args.getInt("index", 0);

Categories

Resources