I am developing an Android application. The content for the application is taken from the webserver using webservice. I am taking the data from webserver and store in mobile db and accessing across the application and its works fine but now problem is while taking more records from mobile db it tooks some time and it application hangs.
Is it possible to maintain the java collection such as hashmap or hashtable to maintain throughout the application until user logout the application and user can add or update the data in collection. If so please guide me.
you should use Application class that ships with Android API .
See this link..
http://www.xoriant.com/blog/mobile-application-development/android-application-class.html
First of all it's better to user db for storing purpose. you should look for optimizing you db querys and the they way you are using it. But anyways you can create a static hashmap or arraylist of your object in your first activity. Then you can use this collection object anywhere you wanted and perform any opration, it will be intect untill and unless you logout of application or any exception occures while working on the collection.
class MylunchedActivity extends Activty{
public static HashMap map = new HashMap();
}
MylunchedActivity should be your first activity. Then by using MylunchedActivity.map, you can work on you map.
i hope this will help.
Regards,
Ravi
use a standalone class or static class to maintain run time static data you need to store.
Created a global singleton in the Application class and was able to access it from the activities I used.
You can pass data around in a Global Singleton if it is going to be used a lot.
public class YourApplication extends Application {
public SomeDataClass data = new SomeDataClass();
// Your JAVA collections...
}
Then call it in any activity by:
YourApplication appState = ((YourApplication)this.getApplication());
appState.data.UseAGetterOrSetterHere(); // Do whatever you need to with the data here.
For more info look at Android Application Class
Here are few possible solutions :
How to store hashmap so that it can be retained it value after a device reboot?
Saving a hash map into Shared Preferences
One is serialize/deserialize and other is using sharedpreference, as your requirement is to save/edit data until user logout.
Related
My application has a list of clients (with only name and age displayed) and I want to be able to edit/add more info about them that is not visible in the list.
So whenever I click on a client, I want to start a second activity with all the info about him.
Can I use an intent for this? Can I pass a full Object (Client) at once with an intent?
I've looked through these two topics, but I haven't found my answer yet:
How to exchange data (objects) between different Android Activities?
How do I pass data between Activities in Android application?
Thanks in advance.
Look at this answer: How to pass an object from one activity to another on Android
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
I would suggest you look into saving these in the SharedPreferences file. Build a singleton AppUtil class and add functionality to save data in the shared preferences there as well as being able to retrieve said data
If you have a large amount of information being stored for the clients then you should look into SQLite as database storage.
The more pratice way is create a class to hold every objects that you need to change between the activities. Like that:
public class MyHolderObjects {
public static MyObjectType mObject;
}
before start the new activity (or whatever you goes to use it), instantiate (create) the object in MyHolderObjects. And use it everywhere you need :). I prefer this approach instead serialize the object.
Im building an android app and in the startup activity i parse a pretty big json file (3.3 mb) into custom objects, or when there was no update i retrieve it from a serialized bytearray. Im dealing with one object with a list of about 500 objects with subobjects, lists etc.
Now i need this data, or some of it in my other activities. What is the best solution for this?
It seemed a lot of data processing to serialize and deserialize using intent.putExtra or using parceable everytime you start a new activity. Is this processing less than i think or is there a way to use your parsing class and don't destroy it so you can use something like
Myclass.get(nrIneed).Mysubclass.getsomestring
?
This is how i did it when using data for logging or something in my parsing activity.
You can use Application class to store this data and you can use it across all the Activity
public class BusinessClass extends Application
{
public ParsedData parsedData = new ParsedData();
}
Then call it in any activity using following code
BusinessClass appState = ((BusinessClass)getApplicationContext());
appState.parsedData.getData();
For more info
http://developer.android.com/reference/android/app/Application.html
You SHOULD NOT use Parcelable for objects which may consume memory more than about 1MB. Otherwise the parsing will fail (at least as per API level 8).
However, in your case, I would recommend you to save/organize the parsed data into SQLite and query it from other activities. This will help your app to eat less memory :)
You may also create a static reference to your object, but since its huge in size, I wouldn't recommend you, because then your app will become an appealing target for android VM to kill - when running under low memory circumstances.
I think you shouldn't use your data as a big Json file. At the first launch you should save your data in a database then only use this db when you need to Create/Retrieve/Update/Delete.
If you really want to use your JSON file, then you should make it static (in your application singleton for example).
Hope this will help you
I have an Activity which first needs to determine the output based on input, with a help of HashMap. I am storing 25 pairs in it.
The problem is that HashMap initializes every time the activity starts. That got me thinking about the best way to store these pairs - should they be in an "external resource", or maybe some other solution - to make pairs persistent?
Putting the data from your hashmap into some persistent storage will probably not help you to get around initializing the hashmap when creating your activity. If your application frequently uses this activity it might be more worthwhile storing the Hashmap as a field in the Application class and then accessing from any activity via the application context.
SampleApplication extends Application{
private HashMap<String,String> mMap = null;
public void onCreate(){
//initialize your hashmap here
...
}
public getHashMap{
return this.mMap;
}
}
To get the map from any activity in your project just use the following code:
HashMap<String,String> map = ((SampleApplication)getApplicationContext()).getHashMap();
If you still need to store the data persistently you can choose one of five methods listed here. HashMap does implement Serializable so I would probably use SharedPreferences if it were me.
EDIT Mert's answer is great if the string's you're using never change, just use string resources instead. But if you need to do a fair amount of manipulation the convenience of a collection might still make the approach in my answer worth it.
It depends how use your Strings..
You can store them on String XML if all fixed and perminent.
You can make a class and store in ApplicationContext if you use only application runs.
You can keep in file/sqlite db or user settings.
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.
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.