getting Context from Intent - java

I have an Activity StaggeredPrenotaTour starting a second Activity Details through an Intent, the class Details contains an AsyncTask class ReservationTask, and after some operations to the network, it has to pass a Java Object back go the StaggeredPrenotaTour class.
StaggeredPrenotaTour at the point where it starts Details:
Intent message = new Intent(staggeredPrenotaTour, Details.class);
message.putExtras(bundle);
getContext().startActivity(message);
Basically I need pass my Object to the current context of StaggeredPrenotaTour, so that I don't have to create a new instance of it but update the contents of the current one!
Unfortunately I've read that there is no way you can get a Context from an Intent, so how is another way to get the working instance of StaggeredPrenotaTour inside Details class?

so how is another way to get the working instance of StaggeredPrenotaTour inside Details class?
You don't.
so that I don't have to create a new instance of it but update the contents of the current one!
It sounds like these two activities should share a common data model, perhaps implemented via a singleton manager. StaggeredPrenotaTour can use the revised data in its onResume() method, which will be called as part of it coming back into the foreground after Details is destroyed (e.g., user presses BACK).
Or, use an event bus (LocalBroadcastManager, greenrobot's EventBus, Square's Otto, etc.). Have ReservationTask raise a ReservationResultsEvent that StaggeredPrenotaTour subscribes to, so StaggeredPrenotaTour can find out the results of the work.

Starting another activity doesn't have to be one-way. You can also
start another activity and receive a result back. To receive a result,
call startActivityForResult() (instead of startActivity()).
For details, read the guide on developer.android.com

Related

Android: Update TextView from Non-Activity Class

I am writing an Android App and i need to display some results from a non-activity class.
Basically my App gets the current location, activity and other things, and on those i run some functions, for example to check if the user has been at that place before.
Anyway, an intent triggers these functions, and at the end of the function I want to update a TextView with the result of these functions.
But it doesn't seem to work from anywhere besides MainActivity. I tried making the TextView static, but that doesn't seem to work, and returning the results to MainActivity is not possible either in since it is not called directly from MainActivity.
Does some have an idea on how to solve this problem?
This is my first android project, so there's still a lot of thing i don't know about. Thank you!
I don't know exactly what your code looks like, but do you have a model class that holds all your data (for example, some kind of singleton)? If so, you could just save the updated text there, and then update the TextView in a callback method.
If that doesn't fit what you're doing, I would considering refactoring your code so that the text you want is sent back to your MainActivity. You mentioned that the method is not called directly, but could your calculations pass the text to an intermediate class, which passes it to your MainActivity?
You should not update the ui drom background thread.
If you want to update the ui from background thread use Handlers,AsyncTask or use some other thread concepts.
If you want to update the UI fro Service or Broadcast receiver for eg you receive a message inside onReceive of broadcasrReceiver now to update the ui use sendBroadcast and inside your activity registet a dynamic Broadcast receiver and then update

Android: Creating a new instance of a new activity

I'm confused regarding with some basic android development concepts, my question is not pointing at a particular code, thats why I dont include any.
Let's say that I have an activity inside of which I have a container in which I load a couple fragments (they are multiple instances of the same fragment), now the activity is populated, and inside one fragment I press a button that opens a new activity, it doesn't matter what may happen in that activity, the thing is that when I press a button it should take me back to the previos activity, I know that pressing the back button or using .finish(); will take me back to my already-populated activity, but I want to know, if that is the correct thing to do, or should I finish the activity as soon as i leave to the next one and when I want to go back create a new instance and repopulate it, if so, where should i store the variables?
Let's say that the fragments that I mentioned are "alarms" for an alarm application, and when I create it I call AlarmFragment newAlarm = new AlarmFragment(); and then I add that alarm to an arrayList in my alarms activity (java class) getListOfAlarms().add(getAlarmsAmount(), frag); which remains on the activity that has the fragment container, the question is, are these variables created in the right place? Because I am leaving them inside the activity itself right? What could happen if the activity is destroyed? I've been told that I should create an SQL database for storing those variables. I am not talking about long term saving but variables that I will be using at runtime
Can someone explain me these concepts a little bit? A link to a place where it is explained will be great too.
Your question seems like it has many parts.
In Part 1, this is what I think you are talking about:
1) how you decide to allow the user to get back to the first activity is really up to you. And 2) what you leave in the Back Stack is also up to you and what you want to define for the users' capabilities within your app. For example, if you want them to only be able to use a button that you define inside Activity 2 container, that is fine. However, you are not required to provide a button in Activity 2, and you are certainly allowed to use the Up Action in the App Bar for navigation. If I were you, I would read more about the Tasks and the Back Stack http://developer.android.com/guide/components/tasks-and-back-stack.html
You also mention this idea of having to "finish an Activity" with .finish(). I don't think that is usually necessary, but it is available to you if you want to use it based on what you decide for your app's logic (and what the user should and shouldn't be able to do).
With the Back button, Activity 1 will appear as if just initialized when you get back from Activity 2. Try it out. Also run some Log statements based on the simple diagram I provided and the Lifecycle "callbacks" (put these methods in your Activities and throw a Log statement in each to get a better sense of where you are in the Lifecycle) http://developer.android.com/guide/components/activities.html#Lifecycle
As for Part 2 of your question, I would try/set-up some of the above first, then start to experiment with a single variable to see what happens to it between Activities. There are a lot of "what ifs" to your question. You don't necessarily have to create a DB to store your variables, but that could certainly be an option. Take a look at the Developer Guide for most of the Data Storage options: http://developer.android.com/guide/topics/data/data-storage.html
If you are concerned about losing data when the Activity is destroyed, I might consider creating a database. Read the following for more info on recreating an Activity when you have gone elsewhere and are returning: http://developer.android.com/training/basics/activity-lifecycle/recreating.html In particular Saving Your Activity State: http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState
There's also an SO post on this: Saving Android Activity state using Save Instance State

Standard approach to pass data among chain of fragments

I am new to android and I want to understand what is the best way to write clean code.
I have the following example:
ActivityA ---> FragmentA (main UI window the user sees)
then on a user's action
FragmentA --->starts---> ActivityB-->FragmentB (the next window the user sees and hides previous one)
then on a user's click:
FragmentB---> starts ---> ActivityC-->FragmentC (the next window the user see that hides the rest)
So at the last step the user sees the layout of FramentC.
In FragmentC in order to populate the widgets of the layout properly I need some data that are available in FragmentA.
What I do now is:
Pass the data as extras in the intent to FragmentB. Some of these are actually needed by FragmentB but others are not, and are passed to FragmentB so that subsequently they are passed to FragmentC via FragmentB (again by intent/extra) if the user actually presses the button that opens up FragmentC's layout
Question:
1) It works but I was wondering if the fact that I pass in the extras of intent to FragmentB data that it does not really need is wrong/hack and there is a better/standard solution
2) When passing data among fragments are these data copies or a single copy is passed arround? I am not clear on that. E.g. in my example if I have a really big object passed from FragmentA to FragmentB (does not need it) and then FragmentB passes it to FragmentC (does need it) do I eventually have occupied 3 x size of the object?
1)Intent is probably the right way to do it. The fact that you need to pass in unneeded data sounds like you may have some really tight coupling in your fragments that may be bad for flexibility later on. Since the data is (I assume) related it would make sense to abstract it into a class and make the class Parcable or Serializable in order to reduce that coupling.
2)Assuming you use parcable/serializable, they're actually copied. This is because an intent doesn't have to go to your app, so the system will turn your data into a form that can be read by a second application. (I'm not sure what format it actually uses, but imagine it as JSON. For all practical purposes it may as well be).
Intents are definitely the way to do it! And just as the other answered has posted, because data is copied, you want to only store as minimal data as possible in your intents. As a general personal rule of thumb, I design my activities to work with only 2~3 different extra values inside intents which usually store a key or an ID and states, and the receiving activity opens and initializes everything based on those few key values.
Think about this things in your solution:
1- to discuss between activity you need intent
2- to pass a big data between activity/fragment : use a pareceable/seriazable bundle passed in intent : http://blog.denevell.org/android-parcelable.html
3- to pass data from fragment to activity you need a communicator interface :
http://developer.android.com/training/basics/fragments/communicating.html

Identifying explicit intent purpose in Android, or building seperate activities?

This may be in the RTFM category but I can’t seem to figure out the proper way to do this. One of my activities shows some random data from a database, it uses some user-defined search-criteria from a previous activity to filter out which data blocks to search from. But it’s main purpose is to display the data, and present the user with a UI to manipulate the data to his will.
The user can also bookmark this random data, and then access it later again (the bookmarks show up in a listview in another activity). Rather than creating a whole new activity with basically the same purpose, I want to reuse the one already created, and just tell it that I want to view some data, rather than search for some new. So what is the proper way of informing an activity of want you want to do? Should that be defined in the Intent extras bundle or is there another way?
Or would the proper way be to create a new activity for this?
You can extend the first Activity like this:
ActivityB extends ActivityA
and then the methods that need to be different in ActivityB can #override the methods in ActivityA, but methods that do the same thing, you don't have to dupe as long as they're protected.

How does a Service communicate with its Activity? How can a Service call a method in the Activity, which started that Service?

Suppose I have an Activity that's a list. It calls a Service when this Activity starts. The Service will do background stuff--download, parse, and fill the list.
My question is this: How can the Service communicate with the Activity?
How can I call a method in the Activity, from the Service? (I'm new to OOP)
The Service is started like this:
hello_service = new Intent(this, HelloService.class);
startService(hello_service);
One of the things my service does is download and parse an XML. After that, it needs to fill a list! So, I want to pass the parsed stuff back to the Activity, and call a method in the Activity to fill that list.
I recently asked a very similar question, best way for service that starts activity to communicate with it, that got a very helpful answer.
Also, consider using AsyncTask instead of a service if the service doesn't need to be alive when the activity is closed. Then you don't need to bother with the server/activity-communication.
You can set activity object to service and invoke methods of your activity from service. But you must to care about thread-safe when you update your UI.
Hope this helps! Tutorial

Categories