First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)
Most of them come with the advice to use android:id instead of just id in the XML file. I did.
From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.
In my location_layout.xml, I use:
<FrameLayout .... >
<some.package.MyCustomView ... />
<LinearLayout ... >
<TextView ...
android:id="#+id/txtLat" />
...
</LinearLayout>
</FrameLayout>
In my Activity I do:
...
setContentView( R.layout.location_layout );
and in my custom view class:
...
TextView tv = (TextView) findViewById( R.id.txtLat );
which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:
...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );
which also returned null.
Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.
So what the heck am I doing wrong?
I'll appreciate any comments.
which returns null
Possibly because you are calling it too early. Wait until onFinishInflate(). Here is a sample project demonstrating a custom View accessing its contents.
Possibly, you are calling findViewById before calling setContentView?
If that's the case, try calling findViewById AFTER calling setContentView
Make sure you don't have multiple versions of your layout for different screen densities. I ran into this problem once when adding a new id to an existing layout but forgot to update the hdpi version. If you forget to update all versions of the layout file it will work for some screen densities but not others.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
This would be wrong
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context);
}
This is correct
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context,attrs);
}
Alongside the classic causes, mentioned elsewhere:
Make sure you've called setContentView() before findViewById()
Make sure that the id you want is in the view or layout you've given to setContentView()
Make sure that the id isn't accidentally duplicated in different layouts
There is one I have found for custom views in standard layouts, which goes against the documentation:
In theory you can create a custom view and add it to a layout (see here). However, I have found that in such situations, sometimes the id attribute works for all the views in the layout except the custom ones. The solution I use is:
Replace each custom view with a FrameLayout with the same layout properties as you would like the custom view to have. Give it an appropriate id, say frame_for_custom_view.
In onCreate:
setContentView(R.layout.my_layout);
FrameView fv = findViewById(R.id.frame_for_custom_layout);
MyCustomView cv = new MyCustomView(context);
fv.addView(cv);
which puts the custom view in the frame.
In my case, I had 2 activites in my project, main.xml and main2.xml. From the beginning, main2 was a copy of main, and everything worked well, until I added new TextView to main2, so the R.id.textview1 became available for the rest of app. Then I tried to fetch it by standard calling:
TextView tv = (TextView) findViewById( R.id.textview1 );
and it was always null. It turned out, that in onCreate constructor I was instantiating not main2, but the other one. I had:
setContentView(R.layout.main);
instead of
setContentView(R.layout.main2);
I noticed this after I arrived here, on the site.
#Override
protected void onStart() {
// use findViewById() here instead of in onCreate()
}
A answer for those using ExpandableListView and run into this question based on it's title.
I had this error attempting to work with TextViews in my child and group views as part of an ExpandableListView implementation.
You can use something like the following in your implementations of the getChildView() and getGroupView() methods.
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_layout, null);
}
I found this here.
FWIW, I don't see that anyone solved this in quite the same way as I needed to. No complaints at compile time, but I was getting a null view at runtime, and calling things in the proper order. That is,
findViewById()
after
setContentView().
The problem turned out that my view is defined in content_main.xml, but in my activity_main.xml, I lacked this one statement:
<include layout="#layout/content_main" />
When I added that to activity_main.xml, no more NullPointer.
I'm pretty new to Android/Eclipse, by mistake I added the UI stuff to activity_main.xml instead of fragment_main.xml. Took me some hours to figure that out...
I had this same problem. I was using a third-party library that allows you to override their adapter for a GridView and to specify your own layout for each GridView cell.
I finally realized what was happening. Eclipse was still using the library's layout xml file for each cell in the GridView, even though it gave no indication of this. In my custom adapter, it indicated that it was using the xml resource from my own project even though at runtime, it wasn't.
So what I did was to make sure my custom xml layouts and ids were different from those still sitting in the library, cleaned the project and then it started reading the correct custom layouts that were in my project.
In short, be careful if you're overriding a third-party library's adapter and specifying your own layout xml for the adapter to use. If your layout inside your project has the same file name as that in the library, you might encounter a really difficult-to-find bug!
In my particular case, I was trying to add a footer to a ListView. The following call in onCreate() was returning null.
TextView footerView = (TextView) placesListView.findViewById(R.id.footer);
Changing this to inflate the footer view instead of finding it by ID solved this issue.
View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
Just wanted to throw my specific case in here. Might help someone down the line.
I was using the directive in my Android UI XML like this:
Parent view:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="home_phone"
android:background="#color/colorPrimary">
...
<include
layout="#layout/retry_button"
android:visibility="gone" />
Child view (retry_button):
<com.foo.RetryButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/retry"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="140dp">
.findViewById(R.id.retry) would always return null. But, if I moved the ID from the child view into the include tag, it started working.
Fixed parent:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="home_phone"
android:background="#color/colorPrimary">
...
<include
layout="#layout/retry_button"
android:id="#+id/retry"
android:visibility="gone" />
Fixed child:
<com.foo.RetryButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="140dp">
In my case, I was using ExpandableListView and I had set android:transcriptMode="normal". This was causing few children in expandable group to disappear and I used to get NULL exception when ever I used scroll the list.
For me I had two xml layouts for the same activity - one in portrait mode and one in landscape. Of course I had changed the id of an object in the landscape xml but had forgotten to make the same change in the portrait version. Make sure if you change one you do the same to the other xml or you will not get an error until you run/debug it and it can't find the id you didn't change. Oh dumb mistakes, why must you punish me so?
Set the activity content from a layout resource.
ie.,setContentView(R.layout.basicXml);
In addition of the above solutions you make sure the
tools:context=".TakeMultipleImages"
in the layout is same value in the mainfest.xml file :
android:name=".TakeMultipleImages" for the same activity element.
it is occur when use copy and paste to create new activity
I have the same problem, but I think its worth sharing with you guys.
If you have to findViewById in custom layout, for example:
public class MiniPlayerControllBar extends LinearLayout {
//code
}
you cannot get the view in constructor.
You should call findViewById after view has inflated.
Their is a method you can override onFinishInflate
My case is none like above, no solutions worked. I assume my view was too deep into layout hierarchy. I moved it one level up and it was not null anymore.
INFLATE THE LAYOUT !! (which contains the id)
In my case findViewById() returned null, because the layout in which the element was written, was not inflated...
Eg.
fragment_layout.xml
<ListView
android:id="#+id/listview">
findViewById(R.id.listview) returned null, because I had not done
inflater.inflate(R.layout.fragment_layout, ..., ...);
before it.
Hope this answer helps some of y'all.
In my case I had inflated the layout but the child views were returning null. Originally I had this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_footer, null, false);
pbSpinner = (ProgressBar) findViewById(R.id.pbListviewFooter);
tvText = (TextView) findViewById(R.id.tvListviewFooter);
...
}
However, when I changed it to the following it worked:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_footer, null, false);
pbSpinner = (ProgressBar) footerView.findViewById(R.id.pbListviewFooter);
tvText = (TextView) footerView.findViewById(R.id.tvListviewFooter);
...
}
The key was to specifically reference the already inflated layout in order to get the child views. That is, to add footerView:
footerView.findViewById...
It crashed for me because one of fields in my activity id was matching with id in an other activity. I fixed it by giving a unique id.
In my loginActivity.xml password field id was "password". In my registration activity I just fixed it by giving id r_password, then it returned not null object:
password = (EditText)findViewById(R.id.r_password);
In my experience, it seems that this can also happen when your code is called after OnDestroyView (when the fragment is on the back stack.) If you are updating the UI on input from a BroadCastReceiver, you ought to check if this is the case.
findViewById also can return null if you're inside a Fragment. As described here: findViewById in Fragment
You should call getView() to return the top level View inside a Fragment. Then you can find the layout items (buttons, textviews, etc)
In my case, findViewById returned null when I moved the call from a parent object into an adapter object instantiated by the parent. After trying tricks listed here without success, I moved the findViewById back into the parent object and passed the result as a parameter during instantiation of the adapter object.
For example, I did this in parent object:
Spinner hdSpinner = (Spinner)view.findViewById(R.id.accountsSpinner);
Then I passed the hdSpinner as a parameter during creation of the adapter object:
mTransactionAdapter = new TransactionAdapter(getActivity(),
R.layout.transactions_list_item, null, from, to, 0, hdSpinner);
I was facing a similar problem when I was trying to do a custom view for a ListView.
I solved it simply by doing this:
public View getView(int i, View view, ViewGroup viewGroup) {
// Gets the inflater
LayoutInflater inflater = LayoutInflater.from(this.contexto);
// Inflates the layout
ConstraintLayout cl2 = (ConstraintLayout)
inflater.inflate(R.layout.custom_list_view, viewGroup, false);
//Insted of calling just findViewById, I call de cl2.findViewById method. cl2 is the layout I have just inflated.
TextView tv1 = (TextView)cl2.findViewById(cl2);
Ways to debug and find the issue:
Comment out all findViewById in your activity.
Comment out everything except onCreate and setContentView
Run the project and see if any layout is set
In my case, I was using activity_main.xml in both my app module and also my library module. So when I performed the above steps, instead of the layout which I designed in the library, the layout inside app module was inflated.
So I changed the activity_main.xml file name to activity_main_lib.xml.
So make sure you do not have any duplicate layout names in your whole project.
The issue for me was that I had two layouts with the same file name activity_main.xml. (The layouts were in different libraries but in the same app) The issue was solved by renaming one of them to a unique name.
For me it returned null because the given control was (programmatically) hidden. When I put a condition to call findViewByID(id) only when the control is visible, it started working again.
For me it was only null when using Evaluate Expression or the Debug Watch View of the IDE.
I have an app which uses only one activity. Inside, I load a fragment with a recyclerview.
Each item in the recyclerview is a dialog fragment. The user can change the items, therefore the recyclerview is updated when the dialog is dismissed.
The problem I'm having now is that when the app is rotated while the dialog is active, the recyclerview will not get updated after the dialog is dismissed.
My dialog gets recreated along with everything in the app when destroyed so I suspect the dismisslistener gets destroyed when recreating.
The dialog exposes a method to set the dismisslistener and then overrides the event to check if one was set.
public void setOnDismissListener(DialogInterface.OnDismissListener
onDismissListener) {
this.onDismissListener = onDismissListener;
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (onDismissListener != null) {
onDismissListener.onDismiss(dialog);
}
}
I then set a dismisslistener inside the onViewBindHolder of the recyclerview
editor.setOnDismissListener(dialog -> {
recycler.getAdapter().notifyDataSetChanged();
}
I'm unsure why this happens, but it seems that after changing the orientation and recreating everything, the recyclerview is never updated. I found out that the method is still called, because inside the ondismisslistener was another function that updated another view with getView().findViewById() which then crashed the app because getView returned null.
I couldn't find any other post about this here.
Does anyone know how I fix the dismisslistener or maybe any other way to wait for a dialogfragment to close?
Have you added android:configChanges="orientation|screenSize" to your activity in AndroidManifest?
Otherwise try (onRestoreInstanceState() and onSaveInstanceState()
Alright I've found out what went wrong.
When recreated, the dialog loses all his variables, just like everything else.
It could be theoretically possible to save those variables in the bundle and fetch them again on recreation, but I have not found a way to do this with an OnClickListener, since objects passed to a bundle must be serializable or parcable.
Therefore, my dialogues are now just dismissed when they do not have any variables via a check in OnCreate.
I'm fairly new to android studio, any help would be appreciated.
I have set up a bottom navigation bar programatically in my MainActivity - what's the best way to set this up with other fragments. I have three fragments, one for each tab in the navigation bar and other fragments which can be opened when buttons are pressed from the navigation bar fragments.
Where do I set up these other fragments? in the same activity that connects the fragments that are connected to the navigation bar or in a different activity.
How do I save the current state of the displayed fragment so that when I move to a different tab and then move back it will be in the same state as when I left it?
My question is, where do i set up these other fragments? in the same activity that connects the fragments that are connected to the navigation bar or in a different activity.
It's really up to you and how you want to display the fragments. You can display them in the same activity or open another activity. However bear in mind that if you open another activity, you will lose the navigation bar of the previous activity (an activity always uses the whole screen)
What does FragmentManager and FragmentTransaction exactly do?
How do I save the current state of the displayed fragment so that when
I move to a different tab and then move back it will be in the same
state as when i left it?
Read about the fragment lifecycle at https://developer.android.com/guide/components/fragments.html#Lifecycle
Specifically, you want to save your state in onSaveInstanceState, and the stuff you save will be sent back to you when the fragment is recreated in onCreate
I'd like to expand on what #rupps said, because I feel like the part about what do FragmentManager/Transaction do is not approached from where you are expecting.
I assume you're using a BottomNavigationView.
Regardless of the (important) lifecycle of Fragments, you have to understand that a Fragment is always attached to an activity (note: this is not true, but let's not talk about headless fragments for now).
The approach you can take is that the Activity layout looks like this: (in pseudo code)
<RelativeLayout width=match_parent height=match_parent>
<FrameLayout
id="#+id/your_fragment_container"
width=match_parent
height=match_parent
layout_above="#+id/navbar" />
<BottomNavigationView
id="#id/navbar"
width=match_parent
height=wrap_content
align_parent_bottom=true />
</RelativeLayout>
This way the BottomNavBar will always be present at the bottom of your layouts.
Now you have to deal with putting the fragments there… Let's say that you need to attach a Listener to that bar, and when you receive a callback that a new menu item has been selected… you can proceed to change the fragment (you will always get one event upon startup or you can force it during onCreate I suppose).
You will literally add a switch/if statement to the onNavigationItemSelected(MenuItem item) method.
and call addFragment(TAG); depending which case it is.
Pseudo-Code for you to get the idea:
private void addFragment(final String tag) {
final Fragment existing = getSupportFragmentManager().findFragmentByTag(tag);
if (existing == null) {
final Fragment newInstance = getNewFragmentInstanceWithTag(tag);
getSupportFragmentManager()
.beginTransaction()
.replace(getFragmentContainerLayout(), newInstance, tag)
.commit();
}
}
You'll also need to provide:
private int getFragmentContainerLayout() {
return R.id.your_fragment_container;
}
and…
public static final String TAB1_TAG = "TAB1_TAG";
public static final String TAB2_TAG = "TAB2_TAG";
public static final String TAB3_TAG = "TAB3_TAG";
protected Fragment getNewFragmentInstanceWithTag(String tag) {
switch (tag) {
case TAB1_TAG:
return Tab1Fragment.newInstance();
case TAB2_TAG:
return Tab2Fragment.newInstance();
case TAB3_TAG:
return Tab3Fragment.newInstance();
default:
return null;
}
}
So what the frog is the FragmentManager/Transaction?
Think of the Manager as a singleton object (one per app) that keeps a reference to your Fragments and can retrieve them for you (if they existed before). It handles Transactions (add/remove/hide/show, etc.) so you can later roll back them (say you add a fragment in a transaction, if you also addToBackStack() then you can simply tell the Manager: pop the last transaction, effectively rolling it back.
It's a monster. It had bugs for over 9000 years and it's not very intuitive; but once you get used to it, you just "use it".
Background:
I am writing an android application with an activity that can be populated by one of a number of fragments. Relatively often, I need to pass a bundle of data to the active fragment so that it can update the UI accordingly.
To get the current fragment, I call getfragmentManager().findFragmentByTag() and cast the returned fragment to my custom fragment class.
The problem:
The above method usually works fine. However, findFragmentByTag() occasionally returns null. Upon further investigation, I have concluded that this will only occur when I run or debug from Android studio (and even then it doesn't happen every time).
Relevant Code:
protected void onCreate(Bundle savedInstanceState){
//Do lots of stuff
currentFragmentTag = "";
getFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
currentFragmentTag = getFragmentManager().getBackStackEntryAt(getFragmentManager().getBackStackEntryCount() - 1).getName();
}
}
});
init();
//Do some more stuff
//this should always be the case
if (currentFragmentTag.equals(LOGIN_FRAGMENT_TAG)) {
((LoginFragment) getFragmentManager().findFragmentByTag(currentFragmentTag)).beginLogin();
}
}
private void init(){
//changed to reflect George Mulligan's advice
Fragment currentFrag = getFragmentManager().findFragmentByTag(LOGIN_FRAGMENT_TAG);
if(currentFrag == null) {
currentFragmentTag = LOGIN_FRAGMENT_TAG;
getFragmentManager().beginTransaction()
.add(R.id.container, loginFrag, LOGIN_FRAGMENT_TAG)
.addToBackStack(LOGIN_FRAGMENT_TAG)
.commit();
getFragmentManager().executePendingTransactions();
}
}
public void updateFragment(){
Bundle dataBundle = new Bundle();
//put stuff in dataBundle
if (currentFragmentTag.equals(LOGIN_FRAGMENT_TAG)) {
LoginFragment currentFrag = (LoginFragment) getFragmentManager().findFragmentByTag(currentFragmentTag);
if (currentFrag != null) {
currentFrag.passBundleToFragment(dataBundle);
Log.d(TAG, "Fragment returned is valid.");
} else {
Log.d(TAG, "Fragment returned is null.");
}
}
//else if a different fragment is active then update it in the same way
}
//Manually open the loginFragment. This can be called from other fragments. My problem always occurs before this is called however.
#Override
public void openLoginScreen() {
if(/*some conditions*/) {
LoginFragment loginFrag = LoginFragment.newInstance();
getFragmentManager().beginTransaction()
.replace(R.id.container, loginFrag, LOGIN_FRAGMENT_TAG)
.addToBackStack(LOGIN_FRAGMENT_TAG)
.commit();
getFragmentManager().executePendingTransactions();
currentFragmentTag = LOGIN_FRAGMENT_TAG;
updateFragment();
}
}
Normally, my logcat looks something like this:
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
...etc.
But every now and then, and only when I start the app from Android Studio, I get something like:
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is valid
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is null
Fragment returned is valid
Fragment returned is valid
What on Earth is going on here?
UPDATE:
I have been able to reproduce this error while disconnected from Android Studio by clicking the app switch button, closing my app and immediately restarting it. Provided I do this quickly enough, it never fails to behave as I described above.
After some more logging and chasing down other issues, I discovered that in these particular cases, onCreate() is being called twice.
My app is designed to run only in landscape mode, in part to avoid issues that come with recreating the activity. It would seem, however, that when the app is closed and restarted quickly, Android never finishes the necessary rotation to portrait mode for the home screen before my app is launched again. My assumption is that this causes the OS to rotate back to landscape after the app is running and thereby restart it.
All of this is fine and dandy, except for the fact that it doesn't explain why findFragmentByTag() sometimes returns null.
Every object in my Activity class should be recreated, right? So shouldn't the FragmentManager be re-initialized as well? Or is getFragmentManager() a static reference to something outside of the Activity itself?
SECOND UPDATE:
I tried George's idea of checking if the fragment had already been added before I call beginTransaction() and, although it didn't solve the problem, I noticed something strange when debugging:
I set a breakpoint at Log.d(TAG, "Fragment returned is null.");. Closing the app and quickly restarting it guarantees that this code will be reached as I mentioned above. Then, if I view the Fragment Manager by calling getFragmentManager() in the Evaluate Expression window, I notice that a `Login Fragment' has already been added, but it doesn't have a tag associated with it.
Setting a breakpoint at Log.d(TAG, "Fragment returned is valid.");in the same app session, however, reveals the LoginFragment is added with a tag as would be expected.
There is no point in my code where I ever add a fragment without setting a tag. Could this have something to do with the activity being recreated and the Fragment manager losing tags even though it holds onto the fragments themselves?
A few things to note on this.
In updateFragment you should really compare your Strings using .equals instead of reference comparison == so LOGIN_FRAGMENT_TAG.equals(currentFragmentTag)as a best practice and to avoid confusion.
Also, the FragmentManager will remember which fragments you have added to it across orientation changes. So in the one example you mentioned where you get into onCreate twice you will then likely have two instances of your LoginFrag on the back stack.
You can avoid this by doing the same lookup you are doing in your updateFragment method and only adding the fragment if it isn't found.
LoginFragment currentFrag = (LoginFragment) getFragmentManager()
.findFragmentByTag(LOGIN_FRAGMENT_TAG);
if(currentFrag == null) {
currentFrag = getFragmentManager().beginTransaction()
.replace(R.id.container, loginFrag, LOGIN_FRAGMENT_TAG)
.addToBackStack(LOGIN_FRAGMENT_TAG)
.commit();
//executePendingTransactions() usually isn't necessary...
getFragmentManager().executePendingTransactions();
}
I'm guessing multiple fragments are used in this activity since you bother having the String currentFragmentTag but if not then it would be better for you to just keep a reference to your LoginFragment as a field on the class so you can avoid the additional lookup of it in the updateFragment method.
Other than that I tried reproducing your error and I cannot so the error might be elsewhere in code you are not showing.
This isn't a direct answer to your question, but a suggestion for avoiding the problem in the first place.
Because the interaction between the Fragment and Activity Lifecycles is so complex and difficult to reason about, I've found that it's much easier if you completely decouple the two.
Instead of obtaining a reference to the Fragment and invoking a method on it directly, I set up a message bus (e.g. Otto or GreenRobot) and in your case, would have the Activity post a message to the bus, and have the Fragment subscribe to that message. Much cleaner, and if the Fragment happens to not be ready (hasn't registered with the bus yet), there's no error condition.
Ok, this should be a comment but, code formatting is ugly as a comment. Perhaps your fragment gets paused.
try this
#Override
public void onResume() {
super.onResume();
updateFragment();
}
I am in a peculiar situtation in my app.
When i app first loads there is a custom listview which is populated with data from the server.I am also using a class which contains different fields for the string data from the server.
When i click an item on the custom listview,the object of the corresponding class is passed onto the next fragment.
That is the current fragment is replaced with a new fragment and the object is passed with bundle.
Now a new listview loads with different tasks.On clicking a task a new fragment with a camera is loaded.
After taking the image and uploading to server, the status in the JSON changes to "COMPLETED".But now when i press back the old listview is shown.
Is there a way to populate the listview on back pressed with new data?
The issue is that I am passing an object right from the first fragment.
Now i need a new object on back pressed,how to pass the new object on back pressed?
When Fragment 2 gets the data, it should pass it along at some point before Fragment 1 is woken.
There are almost a half dozen ways to pass data, and the best way depends on a number of factors like who should own the lifecycle of the data, data pull vs push, dependency between fragments, do multiple components need updating, etc.
I'm just going to advise to simply cache the data on the activity until you learn more about the different methods.
//Fragment 2 puts data to activity
((MyActivity) getActivity).mListViewData = listViewData;
Then the next part of the question is how does fragment 1 get the data. Fragment 1 is hibernating on the backstack. When it wakes up it will call the onViewCreated() method (because it's previous view was destroyed before being placed on the backstack).
In that method, we check if there's new data waiting for Fragment 1.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
MyDataType listViewData = ((MyActivity) getActivity).mListViewData;
if(listViewData != null){
//setData is your own function for replacing the adapters
//data backing
listView.getAdapter().setData(listViewData);
}else{
listView.getAdapter().setData(...defaultData);
}
listView.getAdapter.notifyDataChanged();
}
Override the onBackPressed in the Activity that manages the Fragments. In it you can check if the fragment is visible or not (the one from which an action should be performed if the back is pressed) and then execute your action.
#Override
public void onBackPressed(){
Fragment myFragment = getFragmentManager().findFragmentByTag("MY_FRAGMENT");
if (myFragment.isVisible()) {
String json = myFragment.getJsonData(); //update it locally
if(isUpdated){
Fragment listFragment = getFragmentManager().findFragmentByTag("MY_LIST_FRAGMENT");
listFragment.updateListView(json); //Add this method on your fragment
}
}
super.onBackPressed();
}
Obs.: To use the .findFragmentByTag() you should add tags once you're making the transaction like so:
fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT");
If, for any reason the listFragment has been cleaned from memory, you would have to reload the data anyway so just download the new data again.
To update the ListView please see: How to refresh Android listview? . Note thought that you will need to will need to send a new data set to the list view (which you can do inside the updateListView() method)