Tuesday, 19 February 2013

How to have a global variable in Android

In my related post, I write about how to have a global variable in iOS, now I am working on NYC Subway Time for android, I ask myself the same question. What one does on iOS, he has to do it on Android. It is a good. The imbalance is actually an economic opportunity. Let you guess what I mean :)

First, replace your AndroidManifest.xml with the following code...


    <application
android:theme="@style/CustomTheme"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:name="com.appspot.HelloListView.Common">
>

The crux is the last line, I name a subclass Common. Use another name you like.

Second, add a new class Common.java 

package com.appspot.HelloListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Application;

public class Common extends Application {

Map <String,Stop> stopDict; // a dict of stop by stopId. Used in stop page
Map <String,ArrayList<Stop>> lineDict; // a dict of stops by lineId. Used in nearby page
   
    public Common() {
        this.stopDict = new HashMap<String,Stop>();
        this.lineDict = new HashMap<String,ArrayList<Stop>>();
    }

    public HashMap<String,Stop> getStopDict() {
        return (HashMap<String, Stop>) stopDict;
    }
   
    public HashMap<String, ArrayList<Stop>> getLineDict() {
        return (HashMap<String, ArrayList<Stop>>) lineDict;
    }
       
}


In the above, i have 2 global variables that I need. StopDict and LineDict. I code a getter too. Finally, use the Common class anywhere you want in your other activities...

Common common = (Common)getApplication();
Map <String,ArrayList<Stop>> lineDict = common.getLineDict();
Map <String,Stop> stopDict = common.getStopDict();

.....

stopDict.put(stopId, stop);
lineDict.put(lineId, stops);

Here you go! :)






No comments:

Post a Comment