So if the user is on my app and they click home and go to several other apps and then come back, then the activity will be recreated and getActivity will be null when I call on it in my fragment.
A solution I found was to create a static variable and store getActivity in the onCreateView.
I feel like this isn't a good solution. Is there any other way that I can go about this?
I tried using a non static variable and storing it in OncreateView and onAttach, but getActivity will be null.
Here is the error I will get when I use getActivity if I don't save it as a static variable. I use it in my AsyncTask for ProcessDialog in my Fragment.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
Thanks.
If you are sure that onAttach(Activity activity) also has null, then I suspect you have multiple instance of same fragment at the same time. Print the fragment instance in onResume and check the instances.
Are you implementing the method onActivityCreated? You should use getActivity inside this method.
Another workaround would be use onAttach to keep your Activity.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
Related
I am trying to access the activity on which my Imageview is, so I can use the URL of an Image of type SVG and display it to the user using the GlideToVectorYou library.
GlideToVectorYou.justLoadImage(activity, IMAGE_URI, targetImageView)
But when I try to get access to the activity using R.layout.activityname, a syntax error appears.
this is the code that I'm using
Uri myurl = Uri.parse(match.getFlag());
GlideToVectorYou.justLoadImage(R.layout.item_basketball, myurl, iv_location);
Thank you!
R.layout.item_basketball is just an integer ID for your activity layout - not the activity instance itself. If you want the activity in your adapter you would need to pass it in when you construct the adapter and save it as a class member (example below), or check if your adapter base class already can provide it via getActivity() or getContext() or a similar method.
class MyAdapter(private val activity: Activity) : BaseAdapter() {
fun someMethod() {
// then you can access "activity" in your adapter methods
GlideToVectorYou.justLoadImage(activity, IMAGE_URI, targetImageView)
}
}
and when you create it in your Activity, you would just do something like this
val adapter = MyAdapter(this)
You need a activity reference. R.layout.somethinghere is the layout reference.
On your adapter constructor add a activity parameter and use it inside the adapter.
If you call adapter constructor from an activity, just pass "this" as parameter. If call from a fragment, use "requireActivity" (if using kotlin) or analogous method (getActivity, for example) if using Java
Basically i need to call a method, which refreshes the username in my NavigationBar. I try to call it from another activity SettingsActivity.java, where the user changes his name.
SettingsActivity.java:
// ...
MainActivity tempActivity = new MainActivity();
tempActivity.refreshNBName();
// ...
When i do this i get this exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
I've tried to do this another way:
((MainActivity)getApplicationContext()).refreshNBName();
But this throws another exception:
java.lang.ClassCastException: com.justnothing.nisser.debbie.GlobalVariables cannot be cast to com.justnothing.nisser.debbie.MainActivity
The method that i'm trying to call here looks like this:
public void refreshNBName(){
NavigationView nV = (NavigationView) findViewById(R.id.nav_view);
View headerView = nV.getHeaderView(0);
TextView local_user = (TextView) headerView.findViewById(R.id.actualUser);
local_user.setText(((GlobalVariables) getApplication()).name + " " + ((GlobalVariables) getApplication()).surname);
}
What should i do here? Any help or advice is appreciated!
You wrote this which is not applicable.
MainActivity tempActivity = new MainActivity();
tempActivity.refreshNBName();
Because this is creating new instance of MainActivity class. not referring to the live instance of MainActivity.
You tried another thing, you can't even do this.
((MainActivity)getApplicationContext()).refreshNBName();
Because getApplicationContext will return you context of application class which is not MainActivity.
I have gone through your question, you need not call any method from another activity. If you want update navigation drawer. You can call refreshNBName() on onResume() of MainActivity.class.
So every time user comes back to MainActivity, navigation view will update automatically.
You can create static method in MainActivity and than call the method like this MainActivity.someMethod() but i don't recommend this ! it can lead to memory leak and lots of exception to handle
if your main activity is not alive and is in the pause,stop,destory state there is no point to refreshing the view in main activity and you can always refresh the view to latest data when activity state changed to resume by overwriting onResume method in activity .
and finally i think best way to communicating with activates and fragment is using callback for more information see this link :
https://developer.android.com/training/basics/fragments/communicating.html
I want to get the context or instance of fragment in a activity.I tried following codeļ¼
In fragment:
public static XXFragment instance;
In the onCreate():
instance = this;
In activity:
Context context = XXFrangment.instance;
But it has NullPointerException error.Because I haven't invoked onCreate() of fragment.So how can I do to get the context or instance of Fragment?Hope somebody could help me!
I think there is some error in your way of thinking about Context :-)
First of all, Fragment does not have a Context until added to an Activity. After it is added, the Activity itself is it's Context, so there is no need to extract it from the Fragment. Just use this in Activity code :-)
As a side note, avoid static fields holding complex objects such as Fragments and Activities. In a real, production environment you will never do this, as it leads to so called memory leaks, a big problem in software.
It's good practice to use static method for fragment initializing. Implement this method in your fragment class:
public static YourFragment newInstance() {
Bundle args = new Bundle();
YourFragment fragment = new YourFragment();
fragment.setArguments(args);
return fragment;
}
As you can see, you are able to add parameters in a newInstance() method. These parameters are usually used for adding them as arguments of the fragment.
I am trying to generate a notification from a class, Utilities.java, outside of the subclass of Context. I've thought about providing a SingletonContext class and have looked at posts ike this. I'd like to be able to return != null Context object since the notification can be generated at any given time because it is generated from a messageReceived() callback.
What are there downsides to doing something like this:
public static Context c;
public class MainActivity extends Activity{
#Override
public void onStart()
super.onStart()
c = this.getApplicationContext();
}
//other method somewhere outside this class
public Context getContext(){
return MainActivity.c
}
I don't think it would be any different than putting this on the onCreate(), however, it guarantees that the context is up to date when the activity starts.
The Context keeps a reference to this activity in memory, which you might not want. Perhaps use
this.getApplicationContext();
instead. This will still let you do file IO and most other things a context requires. Without a specific reference to this activity.
Maybe you should overwrite the onResume Method.
If you open a new activity, and switch back, the onStart method will not getting invoked.
Android Lifecycle: doc
BTW: I read about problems with ApplicationContext using a dialog or toast, so if you use the context to create on of these you should use your Activity as context.
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);