Is it possible to save an entire array (or even ArrayList) to the android app data?
As far as I know you can only do stuff like putInt, putBoolean or putString....
But what about more complex data-types?
Is there a way to do that?
Or do I have to convert the whole array to a String first, and then parse it to an array again on load?
for complex data-types use
Bundle bundle = new Bundle();
bundle.putSerializable("key", object);
intent.putExtra("bundle", bundle);
EDit: or for Arrays use
putStringArray(key,value);
I think yuou dont know there is also functions like putFloatArray(key,Value),putStringArray(key,value).You can use those.
If by "app data" you mean SharedPreferences, then no, you can only save simple types.
However you can save application state via Activities' onSaveInstanceState / onRestoreInstanceState as described here: Saving Android Activity state using Save Instance State
Note that this saves state per Activity, so it's best to have a main activity where you save app state.
You can serialize almost any form of data and save it as a byte stream byte[]
After serialization, store with:
putByteArray("key", serializedData);
You need to implement Parcelable. You should have a look at this tutorial Passing ArrayList across activities
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.
I need to save a two dimensional array of custom object in a bundle to restore an activity after a screen rotation but I can't find an example.
You can use Bundle.putSerializable() as arrays are Serializable. You will need to make your custom class Serializable too. Here's a tutorial on implementingSerializable.
How about JSON?
Develop a method to convert your custom object into a JSON object, and add helper methods like "toJSON" & "fromJSON".
Then, you can create a JSONArray for an array of JSON Objects.
A 2D array of this object would simply be a JSONArray of JSONArrays.
Here's an example of what it would look like:
[
[
{"name":"john", "age":25},
{"name":"david", "age": 40}
],
[
{"name":"chris", "age":15},
{"name":"howard", "age":55}
]
]
Not a good idea, mate. I would suggest to save it in somewhere else rather than Bundle. You could still use the same hooker methods onSaveInstanceState & onRestoreInstanceState for the purpose. But, Bundle objects are not designed to store complex data structure. The most it should be handling is a regular object. What you are having is not even an array. It is two dimensions array. You would require a lot of parsing states just to store / restore the data.
How about you put that two dimensional arrays inside your own instance
of Application object and access it from your Activity or
something ? If the device rotates, it will only restarts the Activity.
Not the Application. So, that is one possible solution.
Another one is blocking the Activity to restart when the device rotates. The entire purpose of restarting is to use the different resource for different layout form factor. If you are not using different layout file, you probably won't need the activity to restart.
Anyway, putting complex data outside the Activity scope always helps. There are a lot of state changes and restarting and lifecycle things in Activity. Usually, if you put complex data insides Activity, it is not stable and not reliable because it keeps on changing based on Activity states.
Hope that helps.
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.
I am currently using SharedPreferences for both my preferences and my data. Realizing that getting all of the values for my data out via prefs.getAll() actually gets both of my SharedPreferences which is incredibly annoying.
What is the best route for my data. It is key-value with the keys being dates and the values being floats. (Actually ideally I'd have two floats for every key, but I could traverse two.)
Can I make a Hash Map in my activity and inflate/deflate as normally and send it to my fragments as I need the data?
Your question is asking a few different things, so I'll try answer them all.
For storing data that is too complex for shared preferences, you should look into using an SQLite database. There are some good libraries that make it very simple - check out ActiveAndroid or OrmLite.
If you want to stick with shared preferences, but want to solve the issue of getAll returning the preferences and the data, you can actually create 2 separate sharedpreferences. There is a method getSharedPreferences (String name, int mode) which takes a name. Use the default shared preferences for your preferences, and create a shared preference with a different name for your data.
As for sending data to your fragments, you can use a Bundle. Bundles take all sorts of data, and serializables as well, so that should be no problem. Put your data into a bundle and pass it to your fragment when its instantiated.
How can i Save state of checkbox in single choice list while navigating to another activity & come back to previous activity. Any code snippet would be appreciated. Thanx in advance
Just save the value in SharedPreferences.
Reference is here: http://developer.android.com/reference/android/content/SharedPreferences.html
Example here: http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
You will want to save the current value each time it changes in a shared preference value.
and have initMethod called in onCreate() and perhaps onStart() as well that checks the to see if the value is set in the SharedPreferences and if so initialize to that value.
There are numerous tutorials on SharedPreferences, they are definitely the place to store this kind of data. Otherwise you would need to subclass the Application object which is not a good idea.
There are a couple of things you may want to do.
#1 Pass data into another activity
intent.putExtra("keyName", "somevalue");
We can add multiple entries here. This is a key,value pair. So to receive this data from the receiving activity we have to write this code
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
Read more: http://getablogger.blogspot.com/2008/01/android-pass-data-to-activity.html#ixzz24FoEOTwH
#2 Using Shared Preferences
Tons of info on this.
Easiest way to store data in Android.
http://developer.android.com/guide/topics/data/data-storage.html#pref
http://www.slideshare.net/androidstream/sharedpreferences-tutorial
#3 Using SQLite DB
Databases are great, might be going to far for just saving a checkmark
http://developer.android.com/guide/topics/data/data-storage.html#db