I would like know how can I get and set a value of my activity from my fragment?? is that possible?
below is my activity and the attribute 'myStation' is the value I want get and set from my fragment.
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
public static Station myStation;
In my fragment I can execute 'getActivity()' but I really don't know if I can do that. if I'm wrong, what is the correct process?¿
Thanks.
If the fragment is only used in that activity, then you can simply cast the activity. Otherwise you'll have to verify that it is the correct activity perhaps using instance of.
Let's look at the simpler case:
public class MyActivity extends Activity {
private boolean myFlag;
public boolean getMyFlag() {
return myFlag;
}
public void setMyFlag(boolean myFlag) {
this.myFlag = myFlag;
}
And here would be the fragment to adjust the flag.
public class MyUniqueFragment extends Fragment {
public void updateActivityFlag(boolean myFlag) {
MyActivity myActivity = (MyActivity) getActivity();
myActivity.setMyFlag(myFlag);
}
}
Related
This question already has answers here:
Passing data between a fragment and its container activity
(16 answers)
Closed 5 years ago.
Do not understand fully fragment life-cycle.
Case:
Click FrameLayout from Activity to move to Fragment is working.
Problem:
In Fragment there are two spinners and one SubmitButton, when selected both spinner values, the clicking ofSubmitButton, should display those values from spinner back to the Activity's two Textviews . But, I am unable to do that.
My Solution:
I tried to use Intent, putExtras and then getExtras , but as we are in Fragment, Intent is not going to work for Fragment. Bundle also not helping.
P.S. Need someone who understand good Fragment's life-cycle. Read many posts from stackoverflow and other tutorials. Not found what I meant.
Do not want external libraries as such eventBus
Two ways you can do that
1) Casting getActivity() as your Activity and call the specific method and pass parameter.
public class MyActivity extends AppCompatActivity {
public void setData(String value){
// do whatever with the data
}
}
public class MyFragment extends Fragment{
public void someMethod(){
((MyActivity)getActivity).setData(your_data);
}
}
2) Create an interface and pass the value to activity.
public class MyActivity extends AppCompatActivity implements SpinnerListener{
#Override
public void onSpinnerItemSelected(String value){
// do whatever with the data
}
public interface SpinnerListener {
void onSpinnerItemSelected(String value);
}
}
public class MyFragment extends Fragment {
private SpinnerListener spinnerListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceOf MyActivity)
spinnerListener = ((MyActivity)context);
}
public void someMethod() {
if(spinnerListener != null)
spinnerListener.onSpinnerItemSelected(your_data);
}
}
Note: The safe method is using interface.
I have my activity with one boolean variable public.
I set the variable value to true in other class inside MainActivity, but when my application enters the onPause() function, the variable gets the value false, why?
public class MainActivity extends ActionBarActivity {
public boolean detectedState;
public boolean isDetectedState() {
return detectedState;
}
public void setDetectedState(boolean DetectedState) {
this.detectedState = DetectedState;
}
// i have one fragment in MainActivity...
public static class contentFragment extends Fragment{
// Get and set value of Variable
MainActivity activity = new MainActivity();
System.out.println(activity.isDetectedState());
//out is false
activity.setDetectedState(enable);
System.out.println(activity.isDetectedState());
//out is true
// if now i click in home Button for example, the application is with state onPause.. and my out println is false, why?
}
#Override
protected void onPause(){
super.onPause();
System.out.println(isDetectedState());
//here out is false...
}
}
You should understand that the value of detectedState is set to true for the instance of activity instantiated inside the Fragment class. Variable's value doesn't get affected if you change its value inside an inner class.
You should never create Activity like this
MainActivity activity = new MainActivity();
You can use interfaces to pass data between Activity and Fragment.
You can achieve it by making that variable static but it would be better if you store in the application class.check this
I have an activity with several fragments. In that activity I want to be able to access a function created in a fragment.
Fragment:
public class RandomFragment extends Fragment {
public void randomfuntion (){
}
}
Activity:
public class Main extends FragmentActivity{
Fragment randomname;
public void anotherrandomfuntion (){
randomname. // I want to have access to randomfuntion
}
}
Help?
(RandomFragment)randomname.randomfuntion() should work
I am currently working on an android project and I have an activity, lets call it MyActivity and this activity calls a standard Java class called MyClass.
I need MyClass to finish the MyActivity activity but I can't find out how to do this. I thought I might be able to pass the context to the standard java class and call context.finish() but this doesn't appear to be available.
How can I do this, thanks for any help you can offer.
You can pass the Context, but you will need to cast it to an Activity (or simply pass the Activity itself), although this in general seems like a bad practice.
The most secure solution uses listener and a Handler. It is complex, but ensures a non direct call to finish activity.
Your listener:
interface OnWantToCloseListener{
public void onWantToClose();
}
Class that should close activity.
class MyClass {
private OnWantToCloseListener listener;
public void setWantToCloseListener(OnWantToCloseListener listener){
this.listener = listener;
}
private void fireOnWantToClose(){
if(this.listener != null)
listener.onWantToClose();
}
}
When you want to close your activity you must call fireOnWantToClose() method.
public MyActivity extends Activity{
public void onCreate(){
final int CLOSE = 1; //number to identify what happens
MyClass my_class = new MyClass();
final Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == CLOSE)
MyActivity.this.finish();
}
});
my_class.setOnWantToCloseListener(new OnWantToCloseListener(){
public void onWantToClose(){
handler.sendEmptyMessage(CLOSE);
}
});
}
}
This is secure because Activity is not finished directly by MyClass object, it is finished through a listener that orders a handler to finish activity. Even if you run MyClass object on a second thread this code will works nice.
EDIT: CLOSE var added I forget to declare and initialize this.
Pass the MyActivity to MyClass as an Activity. From there you can call myActivity.finish();
For example:
private Activity myActivity;
public MyClass(Activity myActivity){
this.myActivity = myActivity;
}
public void stopMyActivity(){
myActivity.finish();
}
And in MyActivity:
MyClass myClass = new MyClass(this);
This is risky, because you're holding a reference to an Activity, which can cause memory leaks.
If your java class is a nested inner class, you can use:
public class MyActivity extends Activity {
public static class JavaClass {
public void finishActivity() {
MyActivity.finish();
}
}
}
Otherwise you'll have to pass the java class a Context (i.e. pass it a reference to this, since Activity extends Context) and store it as a private instance variable.
I'm writing an application in which i have a set of code which i want to be available in all of my Activities and ActivityGroups. However, to achieve this, I have extended my activities as:
//custom Activity
public abstract class BaseActivity extends Activity
//custom ActivityGroup
public abstract class BaseActivityGroup extends ActivityGroup
//implemented activities in my app
public class PickUser extends BaseActivity
//and
public class Home extends BaseActivityGroup
Now the thing is, whatever the custom code i write in BaseActivity, I have to write the same in BaseActivityGroup too (as in current implementation). This is prone to code-sync problems and i believe not a good technique.
So, how can i make my extensions in such a way that I only write custom code in BaseActivity and my BaseActivityGroup extends ActivityGroup - which is conceived from BaseActivity class?
If i observe how android does this, so the ActivityGroup in android extends Activity class. And I also want to write my custom ActivityGroup class (known as BaseActivityGroup) that actually extends BaseActivity (which is an extended Activity).
Any ideas/suggestions?
First of all ActivityGroups are bad and should not be used. They are deprecated and it is preferred to use a single activity with multiple fragments.
If you must use an activitygroup you are probably best of by implementing a delegate pattern.
Create a delegate that handles all the common methods such as onCreate, onResume and use that in the bases. In this example I save a reference to the activity in the delegate. This circular referencing might not be the pretties. An alternative is to pass on the activity to the methods in the delegate.
public class ActivityDelegate() {
private Activity mActivity;
public ActivityDelegate(final Activity activity) {
mActivity = activity;
}
public void onCreate(final Bundle savedInstanceState) {
// Do stuff.
}
}
public abstract class BaseActivity extends Activity {
private ActivityDelegate mDelegate = new ActivityDelegate(this);
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate(savedInstanceState);
}
...
}
public abstract class BaseActivityGroup extends ActivityGroup {
private ActivityDelegate mDelegate = new ActivityDelegate(this);
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate(savedInstanceState);
}
...
}
Add an extra final class, called Base.
This one will only contain methods to be called by the other Base classes, such as for instance:
public static boolean createOptionsMenu(final Menu menu,
final MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
return true;
}
Then, in your BaseActivity and BaseActivityGroup classes, you would call:
#Override
public final boolean onCreateOptionsMenu(final Menu menu) {
return Base.createOptionsMenu(menu, getMenuInflater());
}
Hope it helps!
Just Extend everything to BaseActivity including BaseGroupActivity as everything is a child of Activity in android
you can put your login in a separate file under a method. now call the same method from both BaseActivity and BaseActivityGroup if you need activity instance in file . pass context through constructor