How do we provide context for a snippet link?

I have class 'Common' and fragment 'FragmentTest'. "Common.java" is a generic class that has some common functionality for other activities. These functions are accessed in the context of each activity. And here I am passing the context of the fragment to the function in this class. I do like this

In a snippet: -

 Common commonObj = new Common();
 commonObj.myfunction(this.getActivity(),"Do you want to Update ?");

      

And in the class after some operation I am trying to get back to the class fragment.Like this: -

public void myfunction(Context context , String str){    
   //....//
  if(context.getClass().isInstance(FragmentTest.class)){
      **FragmentTest mContext = (FragmentTest)context;**
      mContext.FunctionInFragment();
  }
}

      

But I have a bug in this. Because I cannot use context to link to the fragment. Someone please help ..

+3


source to share


2 answers


First, you cannot use Context

for Fragment

as it Fragment

does not extend Context

. Activity

extends Context

, so when you do this from an Activity what you are trying is working.

I would suggest that the methods in your class Common

should be completely unaware of the existence of yours Fragment

. Thus, they are not "connected" together. You can use a callback interface for this.

Create interface

like this:

public interface Callback<T> {

    onNext(T result);
}

      

Then you can change your method in Common

to the following:

public void myfunction(Callback<Void> callback , String str){    

    //....//
    callback.onNext(null);
}

      



Then when you call a method from Common

from Fragment

, you would do it like this:

Common commonObj = new Common();
commonObj.myfunction(
    new Callback<Void>() {
        @Override
        public void onNext(Void result) {
            functionInFragment();
        }
    },
    "Do you want to Update ?"
);

      

If you need to send data back to the function, you can change the return type of the callback. For example, if you want to pass a string, you must use Callback<String>

and then the method in the original call would look like this:

new Callback<String>() {
    @Override
    public void onNext(String result) {

    }
}

      

And in your class, Common

you would call it like this:

public void myfunction(Callback<String> callback , String str){    

    //....//
    String result = "Hello from common";
    callback.onNext(result);
}

      

+1


source


You can do something like this:

public void myfunction(BaseFragment fragment, String str){ 
  //....//
  if(fragment.getClass().isInstance(FragmentTest.class)){
      FragmentTest fr = (FragmentTest) fragment;
      fr.FunctionInFragment();
  }
}

      



i.e. using some base fragment (BaseFragment) and inheriting from it.

0


source







All Articles