getActivity() vs this.getActivity() in Fragment - android

I am new in Android, and I'd like to know if there is a difference between getActivity() and this.getActivity() in Fragment clases.
For exemple we have a method in a siple class(doesn't extend Activity or Fragment) like:
public static void method(Context context){
... some code
}
If we want to use it, just call it in our fragment class:
MyMethodClass.method(getActivity());
or
MyMethodClass.method(this.getActivity());
I know both are working but I need a proffesional opinion.
Thanks.

They are the same. The this keyword refers to the current object.
public class Car {
int speed = 10;
public void move() {
//using this.speed or speed makes no difference here
}
}

If you are extending from Fragment, both getActivity() and this.getActivity() will call Fragment#getActivity(), so as others said, it makes no difference. Both will lookup for the method in the parent class.
A small correction: tha sample code that you provided:
MyMethodClass.method(getActivity());
would work if method() was a static method. Otherwise you should call it like this:
MyMethodClass.this.method(getActivity());
But that's just basic Java ;)

Use getActivity() keyword instead of 'this' keyword in Fragments

Related

What is the best place to call getContext()?

I was reading fragment documentation and found this:
Caution: If you need a Context object within your Fragment, you can call getContext(). However, be careful to call getContext() only when the fragment is attached to an activity. When the fragment isn't attached yet or was detached during the end of its lifecycle, getContext() returns null
So my question is what is the best place to call getContext() inside the fragment. Like i can call it in onCreateView, or onCreate() or onAttach() on any other place.
I am asking this because recently I got a crash of null pointer using getContext in my fragment. So I thought I should create a global Context object and access it inside the fragment. But then I came across this text from official documentation so I am a bit confused what would be the best place to initialize this Context object.
It all depends what you need that Context for. Sometimes it's just fine to call getApplicationContext(), in other cases it may be needed to use what you are given in onAttach() or call getActivity() if you are in Fragment code. Some are also providing own Application subclass, exposing static method like getAppContext().
In any case, AVOID saving the context as it may lead to memory leak. Get it dynamically when needed only.
As a lot of wrong answers are given, I'll provide what's the best way to handle context inside fragments.
The best solution is checking if the context has a value whenever you need it.
You can do it by wrapping the code in which you access the fragment in 2 ways:
if (getContext() != null) { /* code here */ }
or, as stated in the documentation there's this method:
isAdded()
which: "Return true if the fragment is currently added to its activity." -reference
Again: please AVOID saving the context in a local fragment's variable.
You can do something like this in your fragment.
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
// After this point the context is initialized.
context=activity;
}
NOTE: I don't really get it why it is so not liked this answer.
First af all, depending on the version of android(which was not mentioned), of course the OnAttach is deprecated, it has to be checked.
Next:
I think that if you need cobntext somewhere, you can make a private or protected variable in Fragment, so the context is destroyed when it is garbage collected.
protected MainActivity activity;
Make sure you hold this variable dearly and its reference is not passed to other classes.
This should do the job.
You can implement your logic like this :
private Context mContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public void onDetach() {
mContext = null;
super.onDetach();
}
When you required to use context,
if(mContext != null) {
//Add your logic here
}

How to get the name of the activity from the fragment?

So basically i am going to use one Fragment in two different activities.Except one method of fragment in which I want to change something.So how do i get the name of activity which is using the Fragment so that I can do things depending upon the name of which activity is current.
in Java try:
getActivity().getClass().getSimpleName()
But be careful when you're using getActivity() method from fragment. If your fragment is not attached to activity getActivity() will return null.
in Kotlin try:
activity?.javaClass?.simpleName
It's null safe
The first Ans is great but it's in java so i translate this in koltin
activity?.javaClass?.simpleName
Firstly check if the fragment is still attached to activity, then you can check for activity name:
if(isAdded()) {
getActivity().getClass().getSimpleName();
}
Create your own interface and implement it in both of your activity and finally pass this instance to your fragment.
public interface ActivityListener
{
void onClick();
}
write your code into onClick() method and call this method from fragment.
Use this.getClass().getSimpleName() to get the name of the Activity.
if you're in the context of an OnClickListener (or other inner class), specify the class manually:
MainActivity.class.getSimpleName()
for more details check this link
I think an better solution will be to create an enum which differentiate your cases and sent that enum through the arguments of the fragment. In this way your cases will be very clear and you will know why there is a difference in the flow of your fragment.
If you're in another class and you're trying to get the name of the "initiating class" then you can use Context to access it, like so: getContext().getClass().getSimpleName();
Example:
public String getMyActivityName() {
String myActivityName;
myActivityName = getContext().getClass().getSimpleName();
return myActivityName;
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Toast.makeText(this.getContext(), "myActiveParentClass: "+getMyActivityName(), Toast.LENGTH_SHORT).show();
}
I hope it helps someone...

Need to instantiate an Android activity to pass to another method

I am trying to call this method:
public static void trackFunXStartActivity(Activity a)
{
s.startFunXActivity(a);
}
I'm trying to call it using this code in my LayoutsActivity.java:
public void onStart() {
TrackFunX.trackFunXStartActivity(LayoutsActivity);
}
but I'm not sure how to create or reference the Activity that I can pass to trackFunXStartActivity(Activity a). I don't think I can pass LayoutsActivity as an Activity.
How do I go about instantiating or reference an activity in LayoutsActivity.java to pass to trackFunXStartActivity.
I'm a Android newbie and have done some searches on StackOverflow but didn't see anything to help with this questions.
Thanks
take a static context for the LayoutsActivity like
static Context context;
and in the oncreate method use
context = LayoutsActivity.this
and finally you can use this context in the class where you need

call static void

How do I call my function?
public static void dial(Activity call)
{
Intent intent = new Intent(Intent.ACTION_DIAL);
call.startActivity(intent);
}
Obviously not with:
dial(); /*Something should be within the brackets*/
You should try
ClassName.dial();
The reason is that static methods belong the class itself, not to an individual instance of it. The call to instance.dial() is legal, but discouraged.
you should use your ClassName.StaticMethod.... to call a static method of a class
You can't pass null. You have to send a context object.
Where is your function located? If it's inside an Activity or the such, simply pass "this" as the parameter.
If it's inside an BroadcastListener, or a Service, just change the parameter to Context and pass "this".
What exaclty is the Problem?
If you've got a class like
public class Test {
public void nonStaticFct() {
staticFct();
}
public static void staticFct() {
//do something
}
}
Works perfectly (even if you should call static functions always by Classname.FctName (Test.staticFct())
I guess the problem here is the missing argument.
[Edit] Obviously I am wrong, according to the Java Code Conventions you may use a Classmethod by simply calling it, without using the classname (even if it seems odd, since I would expect an implicit this.staticFct() - but possibly the Java compiler is smart enough)

Calling findViewById() from outside an activity

Is there any way to access a layout's view from a non-Activity-derived class? I'm creating an Accordion class and need to access some of the activity's UI elements. I'm passing in the activity's context to my accordion class's constructor, but the findViewById API is only available from the Activity class. I also don't want to pass in an instance of my activity since that seems to be frowned upon due to potential memory leaks.
I'm pretty sure you can just pass an activity as a parameter, e.g.
public void initSouthViews(Activity activity) {
for (int i = 0; i < southScores_.length; ++i) {
southScores_[i] = (EditText) activity.findViewById(10);
}
}
Here is something that might be helpful.
public interface IViewRequest {
public View requestViewByID(int id);
}
public class MyActivity extends Activity {
private IViewRequest viewRequest = new IViewRequest(){
public View requestViewByID(int id){
return findViewById(id);
});
}
public class Accordion(){
private IViewRequest viewRequest;
public Accordion(IViewRequest viewRequest){
this.viewRequest = viewRequest;
}
private View findViewById(int id){
return viewRequest.requestViewByID(id);
}
}
I have never tried something like this. I also don't know if it won't cuase any memory leaks. But it does what you asked :) "Calling findViewById() from outside an activity"
Activity's context is in fact the Activity class itself. Assuming that this object will live inside only one Activity, it should be safe to pass object of type Activity to it. Otherwise, think about reengineering your Accordion class.
I passed in an instance of one of the Views into the class's constructor.

Categories

Resources