This is an example app to demo a problem with nested fragments and wallet
https://github.com/zumper/WalletTest
Here is the structure of the app in terms of nesting
MainActivity
|
+-> TopLevelFragment
|
+-> NestedFragment
|
+-> SupportWalletFragment
The SupportWalletFragment is configured with a request code of 3333 via
public static final int WALLET_REQUEST_CODE = 3333;
...
WalletFragmentInitParams.Builder startParamsBuilder =
WalletFragmentInitParams.newBuilder()
.setMaskedWalletRequest(generateMaskedWalletRequest("10.99"))
.setMaskedWalletRequestCode(WALLET_REQUEST_CODE);
But when the payment method is selected from the wallet activity the result is delivered via
MainActivity.onActivityResult() with a request code value of 66036
and then to TopLevelFragment.onActivityResult() with a request code value of 500.
That's it. NestedFragment.onActivityResult() is never called with the expected request code of 3333
This problem seems to be a known issue:
http://blog.shamanland.com/2014/01/nested-fragments-for-result.html
https://code.google.com/p/android/issues/detail?id=40537
I can work around the problem in our real code by intercepting the onActivityResult() and relaying the params via event bus or something.
The tricky part is the fact that I don't even get the correct requestCode passed in... This makes all my hacks very brittle.
We have a fragment heavy application and I am unable to reduce the hierarchy more than I already have.
Are there other options for addressing this?
I have talked to google about this.. the answer is that there is no answer. If you are using SupportWalletFragment in a nested fragment situation, activity result propagation will not work (you need to handle it yourself) and your requestCode will not be honored for the MaskedWalletRequest (it will be honored for the FullWalletRequest).
If you are using native Fragments instead of support library Fragments, the requestCode will be honored but you will still need to deal with your own propagation.
We need to continue to use the support library.. So in our case, I am dealing with propagation of activity results manually, and I have set my requestCode to 500 to match the code I seem to get from the masked wallet response result. I think this is the best that can be done given the circumstances. I will update here if I get additional clarity.
Related
Some implementations of it, as well as seemingly some devices, seemingly never return RESULT_OK which equals -1, and just return a misleading 0 while including all the necessary data in the Intent extras
I've seen a lot of Google example code simply not do a condition on the resultCode anymore, but they can deprecate it without breaking anything, given Google's propensity to deprecate completely non functional methods because they like their new name more, they could overload a new onActivityResult to simply not have the resultCode as a method parameter.
I was wondering if there is a technical explanation or a blog post for what that particular message passing protocol has seemed to simply fail, without any update in the documentation saying "hey maybe don't rely on the resultCode following any rhyme or reason"
The result code value is a contract defined by the specific activity's implementation. The only contract defined by Android proper is that the result code is an integer.
Android defined simple constants for success (RESULT_OK) and fail (RESULT_CANCEL), but it's up to the activity to decide if it wants to use those, for what purpose, to use different values, or to not even set a result code (in which case the default is RESULT_CANCEL). In many cases, a simple success or fail isn't complete enough and activities return other int values.
So, the short answer is you need to consult the source of the activity to see what it does (or the documentation, but the contract is unlikely to be defined there).
I'm trying to implement Android pay in app.
The Android pay button must be on a Fragment which is replaced from MainActivity.
WalletFragmentInitParams.Builder startParamsBuilder = WalletFragmentInitParams.newBuilder()
.setMaskedWalletRequest(maskedWalletRequest)
.setMaskedWalletRequestCode(REQUEST_CODE_MASKED_WALLET)
.setAccountName(accountName);
mWalletFragment.initialize(startParamsBuilder.build());
MainActivity mainActivity = getMainActivity();
mainActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.conteiner_AP, mWalletFragment)
.commit();
This id container(R.id.conteiner_AP) is located in a Fragment view
Following these instructions(https://developers.google.com/android-pay/android/tutorial#obtain_credentials_and_a_client_id_for_your_app), I have to get the maskedWallet in the Activity on method onActivityResult by REQUEST_CODE_MASKED_WALLET which was directed above.
But i get the needed data by strange code(328180 and 262644), not my REQUEST_CODE_MASKED_WALLET
Why does it happen? Can somebody help me?
I believe this is because you need to call super.onActivityResult(...) in your Activity onActivityResult method.
Look at the numbers you are getting and how they look in binary:
328180 --> 1010000000111110100
262644 --> 1000000000111110100
Basically what happens is when SupportWalletFragment needs to show UI it fires an Intent with internal requestCode of 500 (Note: do not rely on this number being the same in future releases). 500 in binary is 111110100 which is the common suffix of the numbers you are seeing.
The way the support library directs activity results to fragments is by using the fragment ID as a mask on the upper bits of the request code. That's why you see either 101 or 100 at the start of the two request codes you are seeing. Then when you call super.onActivityResult() the support library extracts the Fragment ID and directs the result appropriately.
If you add this line of code, you should see the result you want.
My program consists of a MainActivity and two fragment activities. I need one fragment to take a String value from the user and pass it to the second fragment.
I am trying to wrap my head around how to do this. Since I am familiar with intents, I found this answer on another post and decided to try it out. Everything looks fine until I get to step 4, when I try to use Intent i = getIntent(); in my second fragment, Studio won't let me use it and says "getIntent(java.lang.String) is deprecated".
This doesn't make sense to me since I have used getIntent() in other programs without issue, and it is letting me use it in my MainActivity (step 2 from the other post) without screaming at me.
I know this can be done without using intents, but I can't figure it out and can't find any really thorough tutorials in order to do so. So I guess my questions are:
Can I make intents work for this purpose still? What should I do to get around this deprecation issue?
Any other advice, explanations, or links to "explain it like I'm 5" tutorials would be very helpful and welcome. I have Googled and read a few, but I am still not understanding this and am becoming increasingly frustrated. It seems like this should be a relatively simple concept.
It is too late for answer but still I am providing my answer for other persons. It is happen because Intent is basically work with an activity. And fragments are not activity, but attached to activity. So simply you need to do this:
Intent intent=getActivity().getIntent();
Having the same problem while passing Object from an Activity to a Java Class.
Here is what I did
This Activity sends data
Salary newSalary = new Salary();
Intent intent = new Intent(ViewData.this,Data.class);
intent.putExtra("SalaryObj", newSalary);
It recieves data(In Data.class)
Here I tried this but Android Studio says getIntent is deprecatedIntent intent = Intent.getIntent();
So What can I use in place of getIntent(), because all the solutions I find on Internet to this problem, uses getIntent().
EDIT:
I was playing around with this and found that I was trying to receive data in Java Class(Not an Activity). But when I used it in an Activity then it works fine. But it takes me to another question that how to send data from an Activity to Java Class(which is not an Activity).
On your onCreate
val bundle = intent.extras
if (bundle != null) {
idEmployee = bundle?.getString("idEmployee", "")
idClient = bundle?.getString("idClient", "")
listAvailable = bundle?.getStringArrayList("listAvailable") as ArrayList<String>
Log.i("list:", "$listAvailable" )
}
It means, that this method could not be supported in further releases. The method is still in the API for backward compability for an unspecified amount of time. Mostly it is dangerous to use deprecated methods or there is a better way to achieve this.
Like it is described here
In this case you should rather use: parseUri(String, int) to achieve this ( according to the android developer api).
Assume that you have a cross platform application. The application runs on Android and on iOS. Your shared language across both platforms is Java. Typically you would write your business logic in Java and all you UI specific part in Java (for Android) and Objective-C (for iOS).
Typically when you implement the MVP pattern in a cross platform, cross language application you would have the Model and the Presenter in Java and provide a Java interface for your Views which is known to your presenters. This way your shared Java presenters can communicate with whatever view implementation you use on the platform specific part.
Lets assume we want to write a iOS app with a Java part which could be shared later on with the same Android app. Here is a graphical representation of the design:
On the left side there is the Java part. In Java you write your models, controllers as well as your view interfaces. You make all the wiring using dependency injection. Then the Java code can be translated to Objective-C using J2objc.
On the right side you have the Objective-C part. Here your UIViewController's can implement the Java interfaces which where translated into ObjectiveC protocols.
Problem:
What I am struggling about is how navigation between views takes place. Assume you are on UIViewControllerA and you tap a button which should bring you to UIViewControllerB. What would you do?
Case 1:
You report the button tap to the Java ControllerA (1) of UIViewControllerA and the Java ControllerA calls Java ControllerB (2) which is linked to UIViewControllerB (3). Then you have the problem that you do not know from the Java Controller side how to insert the UIViewControllerB in the Objective-C View hierarchy. You cannot handle that from the Java side because you have only access to the View interfaces.
Case 2:
You can make the transition to UIViewControllerB whether it is modal or with a UINavigationController or whatever (1). Then, first you need the correct instance of UIViewControllerB which is bind to the Java ControllerB (2). Otherwise the UIViewControllerB could not interact which the Java ControllerB (2,3). When you have the correct instance you need to tell Java ControllerB that the View (UIViewControllerB) has been revealed.
I am still struggling with this problem of how to handle the navigation between different controllers.
How can I model the navigation between different Controllers and handle the cross platform View changes appropriately?
Short answer:
Here is how we do it:
For simple "normal" stuff (like a button that opens the device camera or opens another Activity/UIViewController without any logic behind the action) - ActivityA directly opens ActivityB. ActivityB is now responsible communicating with the app shared logic layer if needed.
For anything more complex or logic dependent we're using 2 options:
ActivityA calls a method of some UseCase which returns an enum or public static final int and takes some action accordingly -OR-
Said UseCase can call a method of a ScreenHandler we registered earlier which knows how to open common Activities from anywhere in the app with some supplied parameters.
Long answer:
I'm the lead developer in a company using a java library for the application's models, logic, and business rules which both mobile platforms (Android and iOS) implement using j2objc.
My design principles come directly from Uncle Bob and SOLID, I really dislike the usage of MVP or MVC when designing whole applications complete with inter-component communications because then you start linking each Activity with 1 and only 1 Controller which sometimes is OK but most of the times you end up with a God Object of a controller that tends to change as much as a View. This can lead to serious code smells.
My favorite way (and the one I find cleanest) of handling this is breaking everything up into UseCases each of which handles 1 "situation" in the app. Sure you can have a Controller that handles several of those UseCases but then all it knows is how to delegate to those UseCases and nothing more.
Additionally, I don't see a reason of linking every action of an Activity to a Controller sitting in the logical layer, if this action is a simple "take me to the map screen" or anything of this sort. The role of the Activity should be handling the Views it holds, and as the only "smart" thing living in the life cycle of the application, I see no reason it can't call the start of the next activity itself.
Furthermore, Activity/UIViewController lifecycle is too complex and too different from each other to be handled by the common java lib. It is something I view as a "detail" and not really "business rules", each platform needs to implement and worry about, thus making the code in the java lib more solid and not prone to change.
Again, my goal is to have each component of the app be as SRP (Single Responsibility Principle) as it can be, and this means linking as few things together as possible.
So an example of simple "normal" stuff:
(all examples are totally imaginary)
ActivityAllUsers displays a list of model object items. Those items came from calling AllUsersInteractor - a UseCase controllerin a back thread (which in turn also handled by the java lib with a dispatch to main thread when the request is completed). The user clicks on one of the items in this list. In this example the ActivityAllUsers already has the model object so opening ActivityUserDetail is a straightforward call with a bundle (or another mechanism) of this data model object. The new activity, ActivityUserDetail, is responsible of creating and using the correct UseCases if further actions are needed.
Example of complex logic call:
ActivityUserDetail has a button titled "Add as a friend" which when clicked calls the callback method onAddFriendClicked in the ActivityUserDetail:
public void onAddFriendClicked() {
AddUserFriendInteractor addUserFriend = new AddUserFriendInteractor();
int result = addUserFriend.add(this.user);
switch(result){
case AddUserFriendInteractor.ADDED:
start some animation or whatever
break;
case AddUserFriendInteractor.REMOVED:
start some animation2 or whatever
break;
case AddUserFriendInteractor.ERROR:
show a toast to the user
break;
case AddUserFriendInteractor.LOGIN_REQUIRED:
start the log in screen with callback to here again
break;
}
}
Example of even more complex call
A BroadcastReceiver on Android or AppDelegate on iOS receive a push notification. This is sent to NotificationHandler which is in the java lib logical layer. In the NotificationHandler constructor which is constructed once in the App.onCreate() it takes a ScreenHandler interface which you implemented in both platforms. This push notification is parsed and the correct method is called in the ScreenHandler to open the correct Activity.
The bottom line is: keep the View as dumb as you can, keep the Activity just smart enough to handle its own life cycle and handle its own views, and communicate with its own controllers (plural!), and everything else should be written (hopefully test-first ;) ) in the java lib.
Using these methods our app currently runs about 60-70% of its code in the java lib, with the next update should take it to the 70-80% hopefully.
I would recommend that you use some kind of slot mechanism. Similar to what other MVP frameworks use.
Definition: A slot is a part of a view where other views can be inserted.
In your presenter you can define as many slots as you want:
GenericSlot slot1 = new GenericSlot();
GenericSlot slot2 = new GenericSlot();
GenericSlot slot3 = new GenericSlot();
These slots must have a reference in the Presenter's view. You can implement a
setInSlot(Object slot, View v);
method. If you implement setInSlot in a view then the view can decide how it should be included.
Have a look at how slots are implemented here.
In cross platform development sharing what I call a "core" (the domain of your application written in Java), I tend to give to the UI ownership of which view to display next. That makes your application more flexible, adapting to the environment as needed (Using a UINavigationController on iOS, Fragments on Android and a single page with dynamic content on the web interface).
Your controllers should not be tied to a view, but instead fulfill a specific role (an accountController for logins/logouts, a recipeController for displaying and editing a recipe, etc).
You would have interfaces for your controllers instead of your views. Then you could use the Factory design pattern to instantiate your controllers on the domain side (your Java code), and the views on the UI side. The view factory has a reference to your domain's controller factory, and uses it to give to the requested view some controllers implementing specific interfaces.
Example:
Following a tap on a "login" button, a homeViewController asks the ViewControllerFactory for a loginViewController. That factory in turn asks the ControllerFactory for a controller implementing the accountHandling interface. It then instantiates a new loginViewController, gives it the controller it just received, and returns that freshly instantiated view controller to the homeViewController. The homeViewController then presents that new view controller to the user.
Since your "core" is environment-agnostic and only contains your domain & business logic, it should remain stable and less prone for edits.
You could take a look at this simplified demo project I made which illustrates this set-up (minus the interfaces).
I've been able to hackily implement the DataDroid library from Google's IO presentation in 2010 into my Android project, and it works great when I have a 1-1 Activity - Request relationship. However, in my FilterSelectActivity I need to make multiple calls to fill the drop-down boxes on my view so the user can select filters. The problem is that the way the library is structured it is not immediately obvious how to make multiple (distinct) calls to the WS using the existing library/callbacks. In particular, I can setup my own callThisMethodWS functions, but there's only one onRequestFinished signature:
public void onRequestFinished(final int requestId, final int resultCode, final Bundle payload)
Now, the requestId is a pseudorandom int that is generated by the specific calling function, so it indicates a "unique" request in terms of its parameters but certainly not a specific request type. resultCode is of no use and I'm not sure what I could do with Bundle other than maybe grabbing an intent extra.
If anyone has implemented DataDroid in their project with multiple WS calls in one activity I would like to know how you differentiated the requests so you could fill your various ArrayLists or ArrayAdapters.
I'm the developer of DataDroid and I've since then released version 2 of datadroid with allows much more easily to send multiple requests from a single Activity or Fragment.
I've also added a new sample (DoubleListActivity in the sample project) which calls 2 webservices from the same activity.
I was able to accomplish this by setting up some constants in the class to identify request types, create a request type member, set that member to the specific constant in each respective WS call, then use that request type member in a conditional in the processing of the result.
In my app I needed something like this too. I have a lot of activities than can have multiple calls to WS, some have more than 5 or 6 differents calls to handle.
To implement this behavior, I added a Request object that contains the request type and the default onRequestFinished callback, that will call OnRequestSuccess, OnRequestError... functions. Then I have an Activity with a SparseArray of Requests, that implements OnRequestFinishedListener and redirects everything to the correct Request. All my activities with WS calls inherit that Activity. I recently implemented this for fragments too.