I am building an app which allows the user to define multiple objects of a specific type, lets call them "Person"'s. The "Person" object is defined as such:
class Person {
public String name;
public int age;
}
These "Person" objects will be serialised and stored within the app, either in SharedPreferences or via a Cloud storage mechanism. This can be considered handled and working.
My problem is that I need an editor interface to allow the user to change the "name" and "age" of any particular "Person" instance in their collection. In order to make my UI feel as much like stock as possible, I would like my editor interface to resemble the "Preference" interface which Android implements. As such I need a way to make a "PreferenceActivity" load and save it's preferences from/to a POJO.
The reason I am looking to do this is so that I have a UI that feels like something the user is used to using. My other choice is to mimic the style and create all the handling code myself, which will take a lot of time.
I imagined the process would be to override the "load" and "save" functions of a "PreferenceActivity" to pull/push the values from a POJO provided "onCreate" via an "Intent" - and the return this POJO as an activity result to the caller.
Is this achievable?
What is the purpose of having it this way? I fail to see why this would be useful nor how it would be feasible with regards to the reference of the pojo containing the data. If it was possible then the saving object would most likely be a generic key-object map, where you would need to extract the data from, which is exactly how the Preferences already work.
If the point of this is just to have the information in a Person object why not just make a method that creates one based on the saved preferences.
----- Additions
If you add a static/singleton data handler(repository) in the App that will contain all the persons while the App is executing, and that it has some kind of identifier for each person. Then you can pass the ID in the intent to the PreferenceActivity which will in turn fetch the person object from the data handler and fill in the values of the PreferenceActivity based on it.
Add another Preference to the PreferenceActivity named "Save" or similar, which you resolve and bind in the activity. When clicked this will fetch the currently entered information (which will be saved in the SharedPreferences) and create a Person instance out of it. It should then pass this object to the data handler which will add it (or update it if the ID is already there) to the repository of Persons. At this time you should probably consider serializing the whole repository and save it, one easy way is just to JSON it all and put it into the SharedPreferences. Don't forget that you need to load this data the first time you access the data handler so that the previously saved persons are accessible.
I would also recommend you create Interfaces for the data handling action in case you want to add new or replace the implementation to for example database operations instead.
This way you can use the PreferenceActivity for add/editing Persons. Even though I would prefer create your own UI for it.
Related
Now I am working on Android application which has one main Activity that is displaying some data via GLSurface. This data can be changed in many ways. For this I have several fragments with some lists of variants with extra logic. Problem is that I need somehow transfer data from one place to another.
For example:
I have fragment with list of elements. I used RecyclerView with custom adapter. I am filling list with data from DB. SomeThingDBEntity for example. When I am getting it from Room DB (using Room entities), but it has some extra fields that only required for showing elements in RecyclerView. I need to send user's choice from adapter to fragment, then from fragment to activity, than activity sends it to some class that incapsulates logic of work with GLSurface. SomeThingGLentity for example. Now I am passing only fields, that requered by SomeThingGLentity for showing data (int, String etc.), but in future this list can grow. I can also send directly SomeThingDBEntity and get required fields only in the end when apply changes to SomeThingGLentity. But is it OK to use Room DB entity this way?
Is there any better way of doing this? I can also create third class which will only contain required fields. But where to place and how to call it? Maybe there are some patterns or guidelines of best way of doing it...
It looks like you need a data mapper. Something similar to this - https://github.com/android10/Android-CleanArchitecture/blob/master/data/src/main/java/com/fernandocejas/android10/sample/data/entity/mapper/UserEntityDataMapper.java.
If you use this approach, you will be able to encapsulate the transformation logic from your DBEntity to your BusinessEntity, and if you will change the data format in one of them, only your mapper will need to be edited.
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'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 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.