简体   繁体   中英

Referencing an activity's property from another activity

I have got a class MainActivity (extends AppCompatActivity). In this class a NavDrawerFragment (extends Fragment) mNavigationDrawerFragment is created.

Then there is a WpFragment which is started on selection of one of the options of the mNavigationDrawerFragment. This WpFragment starts an AsyncTask WpGetTask. On a click event the fragment starts a WpDetailActivity. In a special case WpGetTask starts WpDetailActivity.

If I now select the home symbol in WpDetailActivity, mNavigationDrawerFragment().openDrawer() of the Main Activity should happen. I tried it by using a static class and saving mNavigationDrawerFragment there, which worked for me, but another user gets a NullPointerException when mNavigationDrawerFragment of the static class is referenced from WpDetailActivity.

What different ways are there to call mNavigationDrawerFragment of the MainActivity from WpDetailActivity?

You should not assume data in a Fragment or Activity will persist longer than it is visible - they are not designed to persist. A Fragment can access Activity variables that it is attached to, but only during it's lifecycle and only while it is attached to that Activity .

If you want data to be accessed across Activity s then you should either pass the data in an Intent or else use a datastore (like SharedPreferences ).

You also have other options, but the issue here is essentially that once an Activity is not visible to the user, Android may destroy it and re-create it when needed. This is the reason that you will sometimes get NPE's when you try to access a static (or non-static) class / method / variable in an Activity .

EDIT:

Read the "Process Lifecycle" of Activities:

http://developer.android.com/reference/android/app/Activity.html#ProcessLifecycle

"#3" clearly states that Android may "safely kill its process." This is not a requirement, it is a possibility. That means, for a stable app, you should assuem that it does happen and plan accordingly.

I don't know how to re-produce your special nor have your code neither. So it's hard to figure the issue.

About your case, my understand is: you need to open the drawer from WpDetailActivity right? if so, I would suggest you to use eventbus , send and eventbus notification to MainActivity and call the drawerFragment's openDrawer() method, hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM