Parse an xml once for use across many activities - android

I'm working with SaxParser to parse an xml. The problem is, I have a few screens or activities coded. At the moment, every time I transition to the new activity from a button press for example, the new activity needs to then parse the xml all over again, so it can populate the screen with the specific content.
Is there a way in which I only parse the xml once through the life of the program?
Thank you.

Sure, just parse it once and store what you want to remember in variables.
More completely, you would probably create a class (or classes) classes that represent with properties the same information that is in the xml document. A constructor of the class would take the xml as an argument, parse it, and populate the properties.
Hope this helps.

Sometime earliear I faced the similar problem the problem is that android only allow some of generic datatypes to be sent across activities and if your datatype is not generic then the only solution that I came across it make it public and static

Basically you want a global data to be shared across activities. Then either you can make it static or just create a singleton class and use it across activities. In this singleton class you can store parsed data.
In android there is facility for extending Application class and declaring it manifest file.
So, in any activity you can do getApplication() and access the single instance of that class.
Again this will be similar to Singleton class.

The Application Framework FAQ has a discussion about how to share data structures across activities. Since each activity usually has its own process, it isn't quite as simple as declaring a singleton object.

Related

android globally object reference for all activities

May be its simple question, may be its repeated question, this question s not for upvote and all.
I just want to pass my object from one activity to second and second to third activity. I know there are a lot of ways using shared preferences, Intent bundle from one to another activity.
The reason I want to know that why I can't use an object globally for all my activities and if I can how it is possible?
Thanks
There is a handful of ways in which you can achieve this.
Using a bus/listener:
https://github.com/greenrobot/EventBus
https://square.github.io/otto/
Using the application class (ready the first answer carefully, there are caveats):
How to declare global variables in Android?
And using utility classes with static methods.
Also, if you are have more than one fragment running at the same time, you can create your own interfaces and implement them where you need to receive the information.

What is the best way for fetching data and for passing to another Activity?

Most the app so far I had created, I fetch the data from Network and store it in a singleton class to share data between Activities, when I'm done with those data, I usually clear those setting it to NULL, its work perfectly well
My Question is which approach is better ??
Use parcelable
Writing in database and Query for it
Singleton classes
When exactly we need to use Loaders ?? Why we can't share the data through Loaders ??
If question is repeated ... Please ignore ??
Answer to first part
Parcelable:
The best way to pass data between Activitys or Fragments is by using Parcelable objects. It is said to be more optimised than Serializable. There are couple of libraries/plugins which can help you create Parcelable objects. Lately I was referred to Parceler, created by John Carl. However, I personally use Android Parcelable code generator by Michal Charmas, plugin for IntelliJ IDEA and Android Studio.
DataBase or SharedPreferences:
Using DataBase or SharedPreferences to pass data between Activitys or Fragments sounds weird, and since they are not designed to be used this way, it will only create a mess.
Singletons:
Read this very informative post Singletons are Pathological Liars.
Conclusion:
I recommend Parcelable or if you want to be real lazy then go for Serializable (it's not terrible but it's not great either, according to most).
Don't mess up your code by using singletons, DataBases, static fields, etc. They will come back and haunt you.
Answer to second part:
When exactly we need to use Loaders
Loaders, which will be AsyncTaskLoader when you use, are basically used for situations where we want to retrieve data from the server (via web API), or doing something in background. It is similar to using Thread or AsyncTask but is very powerful as it isn't destroyed on screen rotation, unlike those two.
You should read How to Use Loaders in Android and Alex Lockwood's posts on Loaders (this is a series of 4 posts. Very detailed and great).
It all depends on the way you want to use the data.If you want to use the data in future, as in after the application is killed and re launched you should save it in a database.
I would prefer parcelable over a singleton as I don't have to bother about clear the data.
According to the Documentation we generally use loaders to load data asynchronously and to monitor a the data source for change. To my understanding you aren't doing either of them, hence loaders are not required in this case.
1.Database: If you are going to use the network data in future or you are going to do some query operation to perform filtration according to requirement,it is preferable to go with db.
2.Singleton Class: Most of the developer use this because it is more efficient,the values can be changed and retrieve easily with the help of getters and setters.
Here is a very cool way of passing data to another activity I read this somewhere else on Stackoverflow and always use it now. It may not fit your use-case but it sounds like it will.
For example, say you want to pass a parcelable "DataModel" from ActivityA to ActivityB.
Inside ActivityB create a public static method called 'start' like this.
private static final String DATAMODEL_KEY = "datamodel_key";
public static void start(Context context, DataModel dataModel) {
Intent intent = new Intent(context, ActivityB.class);
intent.putExtra(DATAMODEL_KEY, dataModel);
context.startActivity(intent);
}
To start ActivityB simply call the 'start' method above like this
ActivityB.start(this, datamodel);
Use 'this' if called from an activity, or 'getActivity()' from with a fragment.
This will contain the code for starting ActivityB inside ActivityB, like the private static final DATAMODEL_KEY field and such. To answer your question though, go with option 1 and use parcelables and try out the code I posted above to help with starting the Activity with the data.

Two activities access same variable

I was wondering if I have 2 activities that needs to update and access the same object . What would be the best way to do it? Should I use Application class? Or perhaps Static variable.. Etc?
Another option I can think of is putting it in a base class that both activities inherit. I will initialize the object from shared preferences during OnResume
If your object holds some kind of preference value, don't put it into a super-class. Make it static and/or use the singleton pattern and separate it from your application logic. This provides you with a more modular structure that will be easier to work with. The application class is probably overkill; singletons do the job most of the time. (The Android docs simply states: "There is normally no need to subclass Application.")
You can add it to a super-class, if it is a logical part of it though.
Don't forget to synchronize your object if it's going to be accessed by another/several thread(s).
There are different method to perform such requirement. Singleton is one of them. The other one is extending the application class. If you want a reference outlining all of these methods please see:
What's the best way to share data between activities?

Application arraylist clears

I have an application which has several screens. Lets say A B C D and D might open some external application as well.
All this activities share data, an arraylist with one another and I have created a reference to it in my Application class. (I have created a class which extends Application and referred to it manifest.) So all these are using single instance of arraylist. A initializes the arraylist since its first screen and others might modify it.
The problem is when I test this on emulator nothing gets broken. But on 'some' phones after 3+ screens of navigation arraylist just clears from the heap. No matter how small size is.
Use a singleton class for your ArrayList
Use singleton design pattern or make your object static
With the Singleton design pattern you can:
Ensure that only one instance of a class is created
Provide a global point of access to the object
Allow multiple instances in the future without affecting a singleton class's clients
Declare ArrayList as static in your first Activity then use it from any it will not broke up.

includeed layouts - update in multiple activities

I have an app with multiple activities and multiple layouts. However, one piece of layout is included on several activities. I also have a thread which updates this layout. However, when i switch activity it doesn't work. Since the layout is included the elements have the same ID's, shouldn't it just work? Or do I really need to fetch an object for each element in the layout and feed it into my thread in order to make it update the elements in a new activity?
You should run the update code for each Activity/View, although the XML included is the same, each is a different instance.
My suggestion is on Restart verify is there is any modification to do in each activity, a simple way is to each Activity extend a BaseActivity that has this code.
I include a layout for adverts in my app, but on each activity that uses it, the adverts need to be reloaded.
If I call an activity from one that is using the same included layout when I go back to the previous activity it's still there.
I guess this is what you are seeing....
So you can also save that data inside sharedPreferences (if it is little data and primitive objets or parceable objects).
Also you can extend the Application class and store the data there and update every activity inside the onResume() method. that i believe is the best way to handle this. and this is quite simple to do.
Ask google about extending the application class and he will provide tons of results on how to do it. its an easy way to pass data between activities and/or keep a reference to a single object which you will use throughout the app. Just be carefull to clear it when you wont need it anymore because it will stay in existance untill the application is finished() (which comes with the application extension living thru the whole application lifetime).

Categories

Resources