N.InFOR N.InFOR - 3 months ago 9
Android Question

Call a function in activity A from activity B with getInstance()

I have two activities. I need to call a function created in activity A from Activity B.
What I've done the first time is:
in Activity A, I created my function:

public double [] getRSS(double [] queryC){

if (wifiList!=null){
for (int i=0; i<wifiList.size(); i++){
switch (wifiList.get(i).BSSID){
case "56:2e:27:43:4b:f5" : queryC [0]= + wifiList.get(i).level ; break;
case "20:18:d8:4f:55:e8": queryC [1] = + wifiList.get(i).level ; break;
case "7c:e9:d3:31:8f:b9": queryC [2] = + wifiList.get(i).level ; break;

}
}
}
return queryC;
}


in Activity B:

public class ActivityB extends ActivityA{
.......
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activiteb);
.......
ActivityA w = new ActivityA();
double [] query= w.getRSS(queryC);
.......
}
}


And then sometimes it works sometimes not!
I checked for this answer Can i Create the object of a activity in other class? and I did the same thing:

static ActivityA ActivityA;


and then:

ActivityA = this;
public static ActivityA getInstance() { return ActivityA; }


but I have error just here saying:


Syntax error on token "ActivityA", @ expected
and when I changed the second class to this:
ActivityA.getInstance().getRSS(queryC);

I get this:
The method getInstance() is undefined for the type ActivityA

Answer
        public class YourApplication extends Application {

            private static YourApplication mInstance;

            @Override
            public void onCreate() {
                super.onCreate();
                mInstance = this;


            public static YourApplication getInstance() {
                return mInstance;
            }

 public double [] getRSS(double [] queryC){

        if (wifiList!=null){
            for (int i=0; i<wifiList.size(); i++){
                switch (wifiList.get(i).BSSID){
                    case "56:2e:27:43:4b:f5" : queryC [0]= + wifiList.get(i).level ; break;
                    case "20:18:d8:4f:55:e8": queryC [1]  = + wifiList.get(i).level ; break;
                    case "7c:e9:d3:31:8f:b9": queryC [2] =  + wifiList.get(i).level ; break;

                }
            }
        }
        return queryC;
    }


        }

And in your ActivityA class,

YourApplication.getInstance().getRSS(queryC)

And in your ActivityB class you can access the same way.

Hope this will help you.

Thanks.

Comments