Another way to pass value from one activity to another activity - android

Usually we pass value in android from one activity to another activity by Intent function.Is there is any another way is possible to pass the values from one activity to another activity with out Intent function

Yes. Create a class that extends android.app.Application, then in the Manifest put this class as the name of your application
<application android:name=".ClassNameOfTheClassYouCreated"...>
...activities etc here...
</application>
Now, that class that you created is your application. Its lifespan is all the way as long as the application is running, it holds the activities stack and you can add some custom fields to hold your values. To get the Application instance from an Activity, hit this.getApplication().
Edit regarding fields values being reset (in response to the commend by #hackbod): Using static fields on singletons is the other way to hold global values, but I find the proposed one more elegant. As of the case you mention with resetting values, that can also happen in other contexts (like incoming phone call, orientation change), which raises the need to sanitize (or check for existence, call it whatever you like) values before using them. Always!

Information flow can be realized in various way, all you need is a way to save and retrieve your data.
You can save and then get your data which you want it to flow via static class, file storage, database, or even remote storage by using network.
Intent is the better way. Android creates it, so use it. :)

From http://developer.android.com/guide/topics/providers/content-providers.html :
Content providers store and retrieve data and make it accessible to all applications. They're the only way to share data across applications; there's no common storage area that all Android packages can access.
If you want to make your own data public, you have two options: You can create your own content provider (a ContentProvider subclass) or you can add the data to an existing provider — if there's one that controls the same type of data and you have permission to write to it.

Related

Pass value to non-sequential activity

I'm new to Android development and was unable to find how to pass values to an activity that is not the next screen that the user will see. If I have activities in this order: 1>2>3 connected by buttons, how do I pass a value from 1 to 3? I'm only familiar with using intents on button clicks, which would require me to pass the value to screen 2 and then to screen 3.
Thanks
There are several ways to do that:
1) From Activity1 you pass data though Intent. In Activity2 you retrieve data and pass it within new Intent to Acitivity3.
2) Save data in SharedPreferences in Activity1 and retrieve them in Activity3.
3) Save data in SQLite database which is default for Android. This is a good option if you need to save/query data not once, but many times.
4) Save in Google Cloud or use other services.
You can see here a full bunch of store options in Android. Without performing those actions, storing/retrieving data though the Intent is the only one way.
Note: Make a static variables is such a bad practice, unless it is just constant values or other utilities.
If the chain pass becomes too complicated then you should persist it. My suggestion is using Preferences to save the value. Later you do an existence check in the retrieving Activity, load it, and if needed clear it. This is the method commonly used when storing app Settings values.
If your values become more complicated in structure and more numerous then you'd need to consider database.

Sharing data between services and activities

I have a ListView with a custom ArrayAdapter, that shows orders from an ArrayList. These orders are supposed to be synced with my server. There I have an API, which I am requesting for new orders, and if there are any, I get an XML of the order back. What is the best approach to dynamically update the listView? I do not want to use SQLite to store the orders, because only last ten are supposed to be displayed. With a ContentProvider I am not able to store my custom Order object. And if I wrap the ArrayList into a singleton class and use it in the service as well as in the Activity class for the ArrayAdapter, the ListView is not dynamically updated (probably, because the arrayAdapter makes a copy of the arraylist?). Thank you very much.
Filip
use Intent or Bundle
i'm no sure what you mean regarding the ArrayAdapter not being updated, but i can give you a solution we used in my company.
I have a DataMaanger which is a bridge between the Activities and the Networking or SQLite.
The dataMaanger keeps it's data in memory so it's not in DB or on disk. the disadvantage of it is if your app gets killed for lack of memory and reconstructs itself, the dataManager will be empty, which leaves you with two options, either on every Activitie's death or you main task's activities death you serialize your DataManager's data, or if you are not dependant on any previous data, just make arequest again and update the data manager.
I use broadcasts to notify my activities.
To get an access to the DataManager i don't use a sigletone. i use the Application object, you can extend it and in the Manifest.xml give it's name in the tag, then it will be used instead of the regualr Application object.
You can access it later by using getApplication() method in Activity class.

Android: launch different activities in a stack, using the same class

I have a similar issue with this one:
Android: Multiple activity instances launched by same intent. Bring one uniquely to foreground?
I need to create a stack of activities, all created by using the same class: it is a class defining a news list, only there needs to be multiple children activities that are also news lists, but from different categories. (I do need to have these activities in a stack)
The trouble is I need to change data on each of these activities after they are shown, but I can't find a way to access each one of these activities separately, since they are all using the same class, so if I used static methods, I would change the data on all these activities at the same time. Ideally, there could be a way to use references of each activity, so that I can access methods on each one separately, but I don't think there is a way of doing this.
I might as well pass parameter IDs when starting each activity, and instantiate objects at the same time, for each activity, and using these IDs later access the respective objects' methods...
Edit to clarify: Let me use an example to what I am trying to achieve. I have an A class and I am using this same class to instantiate multiple activities, in a stack. After the creation of these activities, I need to alter data, say, on one of these activities statically, so by calling A.alterData(); , but not when the activities are created, so there is no way of doing this by starting the activities with different data.. Since there are multiple instances of this class, if I do so, this will result on altering the data on all these activities, that are using the A class. Would I be able to somehow use objects and methods to these objects to alter data on different activities that are using the same class?
any other ideas?
You could use an ActivityGroup. It basically holds a list of activities and you need to control the navigation around them. It sounds like it suits your situation. There are many examples of them that can be found through google.
How I would approach changing the data on the other screens is by using shared preferences. You can store whatever data you need in there, and then (through your activity group) when you change screen, the data is refreshed. This is faster and a little more efficient than restarting the intent every time.
Another way is to change the data in the background without the user noticing. This can be done because an Activity group loads all of the Activity it holds and they are always there in the background, running, unless the developer states otherwise.
You could grab a a hold of the appropriate instance of the class you want to change the data on and then just change it.
Does any of this make sense?
I can elaborate more if needed.
I would supply the parameters to each activity, such as:
intent.putExtra("category", categoryId);
That way you aren't managing too much global state.
About changing the data - if you are talking about refreshing the data from its original source, then you should probably be doing this in the onResume() method of the Activity. Check out the Activity Lifecycle.
This has a few benefits:
you will have access to all of the context of that Activity
you won't have to do something nasty like access another Activity's data
you won't waste time refreshing data the user isn't looking at
Even if you have to make updates to the data, there are ways to make sure each Activity "minds its own business".

Working with same data in three activities

I'm not very experienced in android specific components, so I just can't get where I need to look.
I have three activities:
1st gets info about some groups of objects, user selects some of this groups and activity needs to star next activity
2nd activity shows all objects from groups, that user selected at previous activity, here user can deselect some selected objects and then activity starts 3d activity
3d activity allows user to do something with selected objects
My solution is make some singleton model, that let activities get and save information about objects,
but i suppose, that android has some special components to provide data between activities
Help me to find this components^ please
It depends on the type of data that you want to share:
Primitive Data Types
To share primitive data between Activities/Services in an application, use Intent.putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism.
Non-Persistent Objects
For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended:
The android.app.Application class
The android.app.Application is a base class for those who need to maintain global application state. It can be accessed via getApplication() from any Activity or Service. It has a couple of life-cycle methods and will be instantiated by Android automatically if your register it in AndroidManifest.xml.
A public static field/method
An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.
A HashMap of WeakReferences to Objects
You can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity, it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retrieves the object using this key.
A Singleton class
There are advantages to using a static Singleton, such as you can refer to them without casting getApplication() to an application-specific class, or going to the trouble of hanging an interface on all your Application subclasses so that your various modules can refer to that interface instead.
But, the life cycle of a static is not well under your control; so to abide by the life-cycle model, the application class should initiate and tear down these static objects in the onCreate() and onTerminate() methods of the Application Class
Persistent Objects
Even while an application appears to continue running, the system may choose to kill its process and restart it later. If you have data that you need to persist from one activity invocation to the next, you need to represent that data as state that gets saved by an activity when it is informed that it might go away.
For sharing complex persistent user-defined objects, the following approaches are recommended:
Application Preferences
Files
contentProviders
SQLite DB
If the shared data needs to be retained across points where the application process can be killed, then place that data in persistent storage like Application Preferences, SQLite DB, Files or ContentProviders.
yes, you can send data between activities using Intents. Using the putExtra() function for that. If you want to pass your own objects, you need to implement Parcalable class.
There is no problem with using a singleton to share information between your Activities, especially if you need this data to be consistent throughout your whole app.
Alternatively you could use an Intent to pass data between Activities - putExtra().
Yes it does:
http://www.remwebdevelopment.com/dev/a33/Passing-Bundles-Around-Activities.html
Basically you can either send a Bundle or just use putExtra function for that.
try this way please
Intent i = new Intent(this, YourTragetedActivity.class);
i.putExtra("value1", "test1");
i.putExtra("value2", "test2");
startActivity(i);
//// On Your TragetedActivity
getIntent().getStringExtra("value1")
getIntent().getStringExtra("value2")

When to use more Activities

I have an Activity which is an OpenGL view. I also have an xml layout to use for preferences. Until now, to show the preference menu, I just brought it to front by setContentView(). And the same to get back to the OpenGL view.
But is this a case where I should give the preference menu its own Activity?
I guess this would make a few things much easier. For example, the back button would just work, opposed to now where I have to code it or it will just exits the application.
And if this is a good idea, how do I pass data both ways? I have a class that store all preferences. Can I send it to the Activity and back again? Or is the best way to store the preferences in a sqlite database and then use it for passing data?
I find it easier to segregate menus and such into separate activities (unless you are using dialogs etc..) As far as storing data you can do it a number of ways:
Database
StoredPreferences
Intent extras with putExtra/Bundle
Creating an application subclass and storing preferences there
Each have their merit. 4 is pretty easy as you just have to state the application class name in your manifest then call: MyAppClass app = (MyAppClass)getApplicationContext(); and you can then use any variables in MyAppClass via app. 2 is also straightforward.
You already pointed out the main difference: history management.
You can pass data to Activity via Intents putExtra()/getExtra():
Create an Intend and add custom data via Intent.putExtra(..)
Start the new Activity: startActivityForResult(intent).
Inside new Activity you can get extra data with intent.getXyzExtra() (where xyz is type).
When new Activity is done just call setResult(int, resultIntent). Again you can add extra data as described in 1.
Call finish() to end the activity.
In original Activity method onActivityResult will be called. Again extract data from Intent as described in 3.

Categories

Resources