Use a Global ArrayCollection in Flash Builder Mobile application? - android

I am currently developing a mobile application using the latest version of Flash Builder and I need to create a Global ArrayCollection to store information in that is pulled from a local DB. I can pull back the data from the DB fine however I cannot seem to access the Global variable when I try. I have the follng .as file called "Model.as" which is located in a folder called valueObjects and that file contains the following code:
package valueObjects
{
import flash.data.SQLConnection;
import mx.collections.ArrayCollection;
public class Model
{
public var ids:ArrayCollection = new ArrayCollection();
public function Model()
{
}
}
}
Now I want to start populating this ArrayCollection with the info from the database so i import the class into the Default Package mxml doc which will be loaded up first when the app starts by using:
import valueObjects.Model;
Then in a private function I try to access the ids ArrayCollection and populate it however I get the following error:
-1120: Access of undefined property ids.
-Access of undefined property ids
Can anyone please help with this?? Thanks

Have you created an instance of your Model class?
In the classes you want to access it, you should do something like this:
var myModel : Model = new Model();
To share the model instance between classes, you're going to have to do slightly more work. Either by passing around a reference to the same object, or using an alternate method such as creating a Singleton. Many Flex frameworks, such as Cairngorm or RobotLegs, use Singletons if you need an example.

Or easiest way is make array static.
public static var ids:ArrayCollection = new ArrayCollection();
but for this case is Singleton way better.

Related

Saving data in the Application scope in Android

I am building an application in Android with multiple activities. I have a list of an object of type TodoItem that I get from a collection in Firestore database, and I need to access the list from more than one activity to make changes and updates to the list.
To do that, I thought about saving the list in the Application scope (is it a good idea?). For this reason, I created a class MyApplication extends Application (and added it to the Manifest file).
Instead of just adding the list as a class field of MyApplication I thought that maybe I should create a class named DataManager that will hold application-wide information such as my list of TodoItems (and here I ask again: is it a good idea? or maybe there is a better solution?).
At this point I am trying to decide what is a better approach to create and save the DataManager class:
One idea is to make DataManager a Singleton class and save it as a class field of MyApplication. This way, the activities will be able to get the instance of the class using DataManager.getInstance() without the need to get it from the application class with a getter method. In this approach, I will have to create the instance of DataManager and init the field of the application with it in the OnCreate() method of the application.
The second idea is to make it a non-singleton, add DataManager field to MyApplication, and create a getter named getDataManager() in the application class. The getter will check if the field is null (i.e. already initialized or not) and will create a new instance correspondingly. This way, the activities will get the instance using ((MyApplication) getApplication()).getDataManager().
I would like to hear what do you think about my approaches to solve the problem, and if you have any other suggestions or other ways to improve my suggested design.
A nice way when your data source is simple. You can create a singleton class to hold and manage data, including read and write from the singleton.
When you want to use complex data, you can store it to your device disk rather than memory. Android application support you to store your data with file, database, or key-value preference. As for your case, you can use database to store your todolist. Android support sqlite for these work, and we have official orm library called room.
raw sqlite: https://developer.android.com/training/data-storage/sqlite
room library: https://developer.android.com/topic/libraries/architecture/room

General Android Advice: Global Variables

I was wondering what is the best way to handle global variables for android apps. For example, I'm just trying to create a basic login/register system. I've created a user class (that has various attributes like username, password, etc..), so that when we go to the register activity, the User class constructor is called to create a unique user object once all the fields are filled out. I was then thinking of simply having a global arrayList of type User so that I could just loop through all the users on a login attempt.
So far (due to a combined lack of experience in java, and being very new to this android stuff), I haven't been able to implement this successfully. I have a class which I call "globalStuff" which has a bunch of public static variables (i.e. the list of users and current user), which I thought could be accessed from any activity the user navigates to.
There must be a better way to go about this. I've been reading through a few tutorials and a few posts on here, but none address this very basic idea. So what would be the best way to approach something like this?
Thanks for any help!
It's called a static singleton and it looks like this:
public class Global {
private static Global instance = null;
public static Global getInstance() {
if( instance == null )
instance = new Global();
return instance;
}
// additional methods, members, etc...
}
Then you just refer to it in your code as:
Global.getInstance().getUserList();
etc.

Sending an object to another class via Intent

How do you pass an object between views in an android application. I have googled and found that your class needs to implement the appropriate interface. How though do we do it if we do not own the class/object type we are passing (for example from an external library or a random class within the sdk)
I need to pass a HtmlSelect item object (from HtmlUnit open source project) to another class to process it but I cant bundle it up.
Thanks
My best guess is you create a static helper object and pass it like that.
HelperObject class {
static HtmlSelect myHtmlObject
}
source activity:
HelperObject.myHtmlObject = currentHtlmlObject;
startActivity(intent);
Destination activity:
onCreate() {
HtmlSelect htmlSelect = "create a copy copy of HelperObject.myHtmlObject not to have problems and then set it to null"
}
Just use the putExtra() method of your Intent to pass parameters.
At times you need to first "deconstruct" your object into simple elements (Strings, Integers) and then reconstitute it at the other end with getExtras().

What is a good method for persisting objects through an Android app?

I'm trying to persist data objects throughout my Android app. I want to be able to access an object in one activity, modify it, save it, navigate to a new activity, and access the same object with the updated value.
What I'm essentially talking about is a cache, but my data objects are complex. For example, ObjectA contains ObjectB which contains ObjectC. Does anyone know if a good method, tool, or framework for persisting complex objects in Sql?
Put a static field in a subclassed Application. Also inside your manifest, put:
android:name="MyApp" inside your application tags.
Also to access from other files, simply use:
MyApp myApp = (MyApp)getApplicationContext();
See here How to declare global variables in Android?:
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
#Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
You could use an ORM framework, like OrmLite for mapping objects into sql, but it may be an overkill for you situation.
You could also make these shared object Parcelable and pass them between the Activities thru the Intents.
You could also save these objects into the SharedPreferences, so each Activity can access them whenever they feel the need to it, and the objects are also persisted this way. This may mean more IO access though, so take that into consideration as well. You could use e.g. Gson to serialize the objects more painlessly for this.
These are the solutions I'd consider. But whatever you do, don't put this common object into some kind of "standard" global static variable, like using a custom Application class, static field or any implementation of the Singleton pattern, these are really fragile constructs on Android.
Why don't you use a JSON serialization mechanism ?
In association with a static access to your objects you can easily build a lite-weight database with some basic functionnalities:
loadObjectsFromCache
saveObjectsInCache
getObjects
You can also store your objects in differents files, and use a streaming json parser like this one: http://code.google.com/p/google-gson/
It's the same that this one: http://developer.android.com/reference/android/util/JsonReader.html
but can be used even if your application api level is inferior to 11.
It use less memory than the basic DOM parser:
http://developer.android.com/reference/org/json/JSONObject.html,
but with the same speed.

Android: Creating custom class of resources

R class on android has it's limitations. You can't use the resources dynamically for loading audio, pictures or whatever. If you wan't for example, load a set of audio files for a choosen object you can't do something like:
R.raw."string-upon-choosen-object"
I'm new to android and at least I didn't find how you could do that, depending on what objects are choosen or something more dynamic than that. So, I thought about making it dynamic with a little of memory overhead. But, I'm in doubt if it's worth it or just working different with external resources.
The idea is this:
Modify the ant build xml to execute my own task. This task, is a java program that parses the R.java file building a set of HashMaps with it's pair (key, value). I have done this manually and It's working good. So I need some experts voice about it.
This is how I will manage the whole thing:
Generate a base Application class, e.g. MainApplicationResources that builds up all the require methods and attributes. Then, you can access those methods invoking getApplication() and then the desired method.
Something like this:
package [packageName]
import android.app.Application;
import java.util.HashMap;
public class MainActivityResources extends Application {
private HashMap<String,Integer> [resNameObj1];
private HashMap<String,Integer> [resNameObj2];
...
private HashMap<String,Integer> [resNameObjN];
public MainActivityResources() {
super();
[resNameObj1] = new HashMap<String,Integer>();
[resNameObj1].put("[resNameObj1_Key1]", new Integer([resNameObj1_Value1]));
[resNameObj1].put("[resNameObj1_Key2]", new Integer([resNameObj1_Value2]));
[resNameObj2] = new HashMap<String,Integer>();
[resNameObj2].put("[resNameObj2_Key1]", new Integer([resNameObj2_Value1]));
[resNameObj2].put("[resNameObj2_Key2]", new Integer([resNameObj2_Value2]));
...
[resNameObjN] = new HashMap<String,Integer>();
[resNameObjN].put("[resNameObjN_Key1]", new Integer([resNameObjN_Value1]));
[resNameObjN].put("[resNameObjN_Key2]", new Integer([resNameObjN_Value2]));
}
public int get[ResNameObj1](String resourceName) {
return [resNameObj1].get(resourceName).intValue();
}
public int get[ResNameObj2](String resourceName) {
return [resNameObj2].get(resourceName).intValue();
}
...
public int get[ResNameObjN](String resourceName) {
return [resNameObjN].get(resourceName).intValue();
}
}
The question is:
Will I add too much memory use of the device? Is it worth it?
Regards,
I'm new to android and at least I
didn't find how you could do that,
depending on what objects are choosen
or something more dynamic than that.
The Resources class has a getIdentifier() method that will give you the resource ID given the name as a string. This uses reflection, so you would want to cache the results, perhaps using a LinkedHashMap as an LRU cache.
Is it worth it?
IMHO, not really. I would just use getIdentifer() or directly use reflection myself. In fact, I have directly used reflection myself (with the LRU cache) to address this issue.

Categories

Resources