0

My problem is this, I have a static method in which I need to call the method startActivity(). I tried creating another class from which I imported its context but that would not work since I still got the error;

'com.example.app5.menuActivity.this' cannot be referenced from a static context.

 public static void endDay() {
    Context context = getCXT.getAppContext();

    // EVENTS
    conf.day += 1;
    lblDay.setText(String.valueOf(Integer.valueOf(conf.day)));
    //conf.dayRunning = false;
    //startActivity(new Intent(getActivity(), ReportActivity.class));
    context.startActivity(new Intent(this, ReportActivity.class));

    gameLoop();

Im a beginner in Java and Android Studio so forgive me if my question seems out of the blue. However I would like to understand why the new intent "this" doesn't work and how I would do instead.

The second class, which I copied from Static way to get 'Context' in Android?.

public class getCXT extends Application {

private static Context context;

public void onCreate() {
    super.onCreate();
    MyApplication.context = getApplicationContext();
}

public static Context getAppContext() {
    return MyApplication.context;
}
}
Erik77
  • 109
  • 4
  • 12

3 Answers3

3

I have a static method in which I need to call the method startActivity()

Have the static method accept an Activity as a parameter, and call startActivity() on it.

I would like to understand why the new intent "this" doesn't work and how I would do instead.

Quoting Oracle's Java tutorials:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

There is no this in a static method, however, which is one of the reasons why that code will not compile.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

Rather than

Context context = getCXT.getContext();

you can change this line to

Context context = getCXT.getAppContext();
Tgisan
  • 21
  • 1
  • 11
0

Yes please try below

context.startActivity(new Intent(context, ReportActivity.class));

we can't use 'this' in static methods. It can used in non-static methods as they are object level methods. Static is like a class level, that is reason why we don't need object to access the static methods. We can call static methods with Class name directly.