Bilbo Baggins
Bilbo Baggins

Reputation: 3692

Android: Cannot access public static function or public variables from another class

Here is the declaration in 'MainActivity.java'

private static String competition = null;

I've created a setter function which adds value to it.

public static void setCompetition(String competition1) {
    competition = competition1;
}

I've created a getter function to get the value in another class from the same package:

public static String getCompetition() {
    return competition;
}

However it returns null.

Here is how I tried to use it in a function public void onReceive(Context context, Intent intent) {

with in the class AlarmNotify which extends BroadcastReceiver:

       final String competition = MainActivity.getCompetition();

Upvotes: 0

Views: 1214

Answers (2)

Bilbo Baggins
Bilbo Baggins

Reputation: 3692

Here is the mistake I did: I was calling a network based async task, which takes few seconds to retrieve the data. It works in the background.

I was calling another function which was trying to access these values. It was being fired instantaneously, even before the async task could run. That is why it was returning null.

Async task hadn't returned those values.

Ultimately I put the call to the other function in the postExecute method of the Async.

Hope that helps anyone who makes the same mistake as I did.

Upvotes: 0

MoveFast
MoveFast

Reputation: 3025

I think you are not invoking setCompetition anywhere. To validate that, try with this piece of code -

public static void setCompetition(String competition1) {
    System.out.println("Set competition to "+competition1);
    competition = competition1;
}

If you do not see any printed message, then setCompetition is not being invoked. Ensure that this is being invoked.

Upvotes: 0

Related Questions