Transfer values between two Activities with static fields - android

Is there any disadvantage in transferring values from Activity A to Activity B with static fields of a third class instead of the ExtraBundle?
In my application, sometimes I have like 15 - 20 values that I need to transfer between two Activitys. In my oppinion, it is more lucid solving this with static fields from a sort of TransferHandler.
At the moment, I have one disadvantage in mind: When a value is not put into the Extras before starting Activity B, I will get an Exception. Solving it with static fields, it it possible that I forget to assign a value, and if that value was assigned before from somewhere else, it might be that a wrong value is used in Activity B. Nonetheless, I think this is a "programmer problem" and not a "program problem". So are there any further minusses or am I free to choice a way? How's with the performance of the two variants?

First of all, if you plan to use static values, you should use your Application class to do this (because Android system assures you that it is a true singleton)
Thus, you can store your datas in attributes of your custom Application class, and use specific methods to store and get these values.
This will ensure you can't "forget" any values.
Also, with 15-20, I will strongly advice you to make a specialized POJO class to store all this...

I think the biggest disadvantage with using static classes for passing information in android is that static fields and objects can be cleared by the system at any time. That means that any static non final value can ALWAYS be null.
So it will probably work fine most of the time, but if you don't make sure to handle these null situations and your users start using your app they'll get a null pointer exception crash once in a while because the system decided it needed that memory stored in those static fields.
The best way for passing data between activities is by my opinion by using Intents, see here for a good example. Alternatively use a database or the the sharedpreferences.
Google also have a good read about pass data between Activities/Services here.

You cannot use a third class to transferring values form one activity to other. Here is the problem with it. You create one object in the activity-a then you store some values into it. Then after for using the values you need to create one more object in the activity-b then the object created in activity b will not be having the values you assigned in activity-a.

You can use SharedPreferences class to store valuo of variables:
SharedPreferences settings = getSharedPreferences("shared_pref", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = settings.edit();
// With editor you put data
editor.putString(firstName, "John");
editor.putString(lastName, "Smith");
editor.commit();
You can access this data in all activities:
// With settings you access to data in different activities
SharedPreferences settings = getSharedPreferences("shared_pref", MODE_WORLD_READABLE);
String firstName = settings.getString(firstName, null);
String lastName = settings.getString(lastName, null);

Related

A refernce sheet for android project

I have a NFC tag and I have to read from it a text, and save this text some where to use the parameters in it in many activities and fragments.
this parameters I should be able to delete or overwrite it when a user decide to exit the program or to read another tag.
I didn't like the idea to transfer this parameters over the activities since they are constant in the whole session for example the ID number of the tag and the manufacturer of it.
I thought also to creat a file in Assets and read it every time, but I thought there should be better way to solve this problem.
There are several ways to how you make the values accessible throughout the project.
Using Shared Preferences:
You can use shared preferences, where you can create variables for your fixed values such as TAG_ID and MANUFACTURER_ID. Every time you tap a new card you can update them, or anytime you expect them to be changed.
Using a Model Class:
You can also create a Model Class (May be Singleton as well) which holds the TAG_ID and MANUFACTURER_ID. Initialize the object of this model class every time there is new Tag tapped. You can also access/change them anytime using getters and setters.
Using Static variables:
You can define static variables to store your desired values and you can simply access them wherever and whenever you want to. This will workout only with less numbers of variables. Increased static variables could affect the performance.

"global" array with different data types - Android

I'm new in programming for Android so maybe my question will be very easy to solve but still. I'm trying to make an array of different data types :
I have to add there :
int number
String name
int number_2
int time
int total
And my question now is how to implement it in easiest way, and how to get data from it. In case that I have to get a different records for this variables and store it into list .
Also have a question about way how to keep all values which I handle inside of my array.
I have to keep it because in my program I have to go back to other activities go forward to another and again collect data and add it to my array.
What will be the best and easiest solution ?
Thanks in advance for help
You could create the Array as an Array of Objects. All other classes are derived from Object, so you'll be able to store all types of objects in your Array. However, you would have to check the type of an object you get from the Array, before you'd be able to safely interpret as an object of a specific class. Moreover, you would have to use Integer instead of int.
If all (or at least multiple) of your elements you are intending to store in the Array are belonging to one (physical) entity, you could create a custom Class that holds its own properties as class members, and fill your Array with a list of instances of this Class.
Moreover, if you plan to add elements to your Array, you should use a List instead, e.g. an ArrayList.
As for retaining your data, you would have to either store it in a database, or save it to a file. In either way, you will have to save it upon close of the Activity, and load it again once the Activity starts
To pass the data across activities you will need to pass them using objects you can store in an intent. Seems like the best way to handle that is to either create a PREFS file to store the data or to create an object that extends Parcelable like here:
https://stackoverflow.com/questions/18593619/android-parcelable-object-passing-to-another-activity
Parcelables are preferable assuming you need all the data in a single object, you do not want to "putExtra" a bunch of fields and you also want to be sure data can pass from one activity to another. Otherwise, a simple Util class that reads and writes to a PREFS file is the way to go:
android read/write user preferences
A database is always another option, but seems well outside the scope of your question.

Share a value across all views of my activity

This question is more like a discussion about how you guys would do it.
I'm developing an application that has an Avatar Creation, but this creating occurs across two different Activities.
In the first one the user selects whether is man or a woman and a name, in the next Activity the user has to select his face, hair, clothes and etc.
Since the views for hair and etc changes if the user is a man or a woman how would you implement a way to pass the gender value to all the Views?
I was thinking about using a static member to hold the value so I could access inside my views, or maybe I should use SharedPreferences to do it.
I think using the SharedPreferences is a more elegant way to do it but I'm wondering if there isn't any other better and more elegant way of doing it.
Has anyone thought about other implementations?
If its only a small information like "gender" i don't see much harm using "Static" variable(Ofcourse the static variable will become null if your app crashes when its in the background).
SharedPreference will come good if you want the information to be persistent(But i don't see you need this).
One more choice is you do can extend the application class to store the static data across activities.
You could pass the gender to the next Activity with start activity Intent. Example:
Intent intent = new Intent(this, NEXT_ACTIVITY.class)
intent.putExtra("gender", genderVariable)
startActivity(intent);
And retrieve the value in NEXT_ACTIVITY class on onCreate() like this:
String genderVariable = ""
Bundle parms = getIntent().getExtras()
if (parms != null) genderVariable = parms.getString("gender")
Then, pass gender to all your views and persist the genderVariable on SharedPreferences or onSavedInstanceState bundle. I prefer onSavedInstanceState.
Hope it helps.
I think there are many ways of which 4 I think are better. It ofcourse depends on what kind of data you want to store.
For Lists or hashmaps, using a singleton class would be helpful.
Using a static class would help, but might leak memory. You should be very careful and always check using logcat, MAT before releasing your app.
Using preferences or database.
Passing data as Intent extra (parcelable if needed).
Using SharedPreferences would be the better way to share some global values across the application.

Passing/Using non primitive objects between Activities

I need to pass a List of my objects between activities. I do not want to use parcelable or serialize the data each time. I also do not want to save it in a local file or database. That probably leaves me with using static objects.
Lets say I to use ListA between activities Activity1 to Activity2. I ca
Approach1: Create a static ListA in one of those activities and do all my stuff of that static ListA.
Approach2: Create a static list in another class which I use just for storing this List and doing all my stuff on this list. But this means that this stays as long as my process is running and I have to manually set it to null when I do not need it.
Approach3. I am extending the above class to implement it using a static HashMap.
I have two methods one to store the list in a static HashMap using a unique key and another method to retrieve the list and remove it each time data is retrieved so that the List is no longer present in the static HashMap. So we essentially have to pass only the random key generated to store data between activities which I can pass as an extra using Intents.
Will there be any issues when I use any of the above approaches and which will be the best approach.
I'd consider creating an Application object and using it like a singleton to access your data. I've described the approach here: http://chrisrisner.com/31-Days-of-Android--Day-7%E2%80%93Sharing-Data-Between-Activities. Some people don't seem to like using the Application object in this manner but it makes more sense to me than putting a static object on an Activity.
Uggg statics! Man I wish all developers understood global variables are bad and how they make your program more brittle and your life hell. We only been talking about how bad they are for 30+ years, but unfortunately no one figures this out until they've utterly hung themselves on them.
First I'll say serializing your data is fast. There are great tools out there that will serialize your objects quickly that you can use I prefer http://flexjson.sourceforge.net for this.
So if you are just outright opposed to this you can pass this object through the Application by subclassing it, declaring your implementation in your Android Manifest, and each activity has access to the Application instance:
public class MyActivity extends Activity {
public void onCreate( Bundle bundle ) {
MyApplication application = (MyApplication)getApplication();
Object anInstanceFromAnotherActivity = application.getSomeInput();
}
}
The downside to this is when your application is reclaimed if the user returns to your application the memory is gone, and you can't get that input you might need of your screen. Android framework is trying to make you serializing things in the bundles because if it decides to destroy your application you can always rebuild yourself from the bundle. Now there are short cuts you can take like redirecting people to start over if the Application has been reclaimed, but those depend upon your program and what its doing if they make sense.
That's where using serialization wins out over all other forms of persistence (parcelables, files, databases) because it can be done in one line of code.

Android : Static variable null on low memory

I have an application which has some static variables.
These variables are stored in an independent Class named DataContext.
These variables are initialized from raw files at the application start (a method named DataContext.initConstant() is called in the onCreate() of MyApplication which extends Application).
(EDIT : the initConstant method use an AsyncTask to load this data from files).
When my application comes to the background for a certain time or when my application used to much memory, these static variables become null.
How can it be prevented?
If not what should I do with my static variables?
I have other data which are stored in static variables to be used across different activities, but I clear them or pass them to null in the onLowMemory() of MyApplication.
What is the best way to keep some data accessible between activities if these data are too big to be serialized in an Intent, a database can't be used (for whatever reason), and can't be stored in files through serialization either?
You can't. Android needs to free up memory from time to time. Imagine if all applications had a ton of static data that is supposed to be resident forever - how would you fit that in memory? It's a mobile phone. It doesn't have virtual memory.
(and 3): Anything that is intended to be persistent needs to be stored, either via SharedPreferences, a Sqlite database, or a file.
Most likely the issue is that your application is being killed while it is in the background, and then recreated when you come back to it. Check out the Activity Lifecycle documentation on when this might occur for a single activity. You need to make sure that you move anything stored in memory to more permanent storage at the correct point in time to avoid losing that information if the app gets killed.
I'm not sure what exactly you are storing, but it sounds like using Shared Preferences might work well. This page on Data Storage explains a number of different ways of more permanently storing data, including Shared Preferences.
If you weren't using raw files, I'd advise initializing when the class is loaded.
For instance,
public static Map<?,?> myStaticMap = new HashMap<?,?>();
static { //fill myStaticMap }
You do have some bigger concerns to worry about if you are loading files that way. For instance, what about I/O errors, or latency issues? You will get warnings in gingerbread (if you enable them) for doing I/O in your main thread. Perhaps you should have an object to retrieve these values instead of a class with static fields. (perhaps with a static cache, although you should synchronize on it before checking/changing it)
I assume this is a data cache problem.
Storing data in static class is not guaranteed to work when user swap apps often. Android system will reclaim any background activity when memory is low. Static class is definitely among this category.
The proper way to do it is to use sharedPreference to persist cache data.
You can create your own getter and setter of the data you want and wrap it around sharedPreference object. When you access using getter, you should always check if the value is empty or expired. You can store an update_time when using setter.
For activity specific data, you can just use getPreference(permission), if you want to share data across activities and other applications components, you can use getSharedPreference(name, permission).
Normally, the permission will be MODE_PRIVATE such that the data can only be accessed within your application.
You should group data and store in difference sharedPreference object. This is good practice because when you want to invalidate that group of data, it is just a matter of one liner.
editor.clear(); editor.commit()
If you want to cache complex object, you should serialize it. I prefer JSON format. So you need some conversion mechanism in place. To do this, I will create my data object class extending JSONable class. JSONable class will have toJSON() method and readFromJSON(). This is convenient when restore and serialize data.
I store a User object and a Client object in my static scope. I have noticed from time to time the reference becomes null. So now in my getters I check to see if this value is null and if so I restart the app.
Intent i = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
I could have also chosen to reload the Client because I store the Access Token in prefs however I do so much initialization that I decided restarting the app would the best idea.
In your onResume() method you could query the static data to see if it is present and if not, load it back in again.
Instead of using the static variable u can use the shared preference for storing the value.
Note: for shared preference also you should not give heavy load.
I have solved this problem by having the super class with getter and setter function for storing and retrieving shared preference variable.
All class in my application extended the super class instead of activity.

Categories

Resources