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.
Related
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
I have an android app with one "home" or "main" activity that relies on fragments to accomplish several tasks. This data relies on information retrieved from a server (mine, and presumably a substantial amount by google maps).
I would like to structure my code such that several other activities (ie. preferences) can temporarily take focus before returning to the main activity.
Currently android destroys and recreates the main activity, which means bandwidth is wasted every time.
There are several notable intent flags which 'solve' this problem (Intent.FLAG_ACTIVITY_REORDER_TO_FRONT and Intent.FLAG_ACTIVITY_CLEAR_TOP), however they only appear to be useful when transitioning back to the main activity, which means I have to #override the system behaviour for both onKeyDown() and onBackPressed(). I would really prefer not to do this in case it causes other issues or eventually becomes deprecated.
Is this safe? Or is the better solution to force my application to create a serialization (savedInstanceState) of the main activity and all fragments anytime another activity temporarily takes the foreground?
Using saved instance state is the proper approach here. That will let you persist the information retrieved from the server when the activity gets re-created.
You only need to implement code to save / restore the instance state in the fragment or activity that holds the data. If you want to share that data across all your fragments, you can place it in the activity and add code to save the instance state of the activity. Then you can access the data that's stored in the activity from your fragments with ((MainActivity)getActivity()).getData().
For code to save and restore instance state, take a look at:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState
http://developer.android.com/training/basics/activity-lifecycle/recreating.html#RestoreState
If the data you need to persist is really large, you can use a retained fragment instead, as explained here:
http://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject
Another trick for large data objects is to use a singleton class to store the data while the orientation change takes place.
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
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
In my case, I have two classes MenuActivity, MinhaEscolaActivity.
There is a method in MenuActivity called quemSouEu, it is a non static method.
It also needs some properties defined on MinhaEscolaActivity's constructor method.
If I instanciate a new object of MinhaEscolaActivity on MenuActivity, these properties will be null, and i'll get NullPointerException.
Is there a way to use the method quemSouEu from MenuActivity class?
You shouldnt create an activity object by yourself. An activity is a main android component that is meant to be created by the system.
If you have some functions to be shared between activities, you should create another class, and instantiate an object in your activity.
If you also have data to share, you can think about some of the standar ways of sharing data, as you can read in this answer
What are the objects that you are creating on the second class constructor? you could start the activity and get the result, but youshould only do this if actually you need to show a new view or interact with the user in a diferent way, you shouldnt tell the system to run a new activity just for calling a function.
You can use intents to pass values between activities. You should never create an instance of activity class. Take a look at Raghav Sood's answer in the below post
Can i Create the object of a activity in other class?
Your storage options
http://developer.android.com/guide/topics/data/data-storage.html
Store the data and retrieve it when you need. Read the docs before choosing one.
You can pass data from MinhaEscolaActivity to MenuActivtiyusing intents and execute the method in MenuActivity it self