-1

I need intent in static class. But when i write intent, MainActivity is red underlined.

imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(getItemId() == 0){
                    Intent intent = new Intent(MainActivity.this, Spacex.class);

                }
            }
        });

com.company.app.MainActivity.this cannot be referenced from a static context

What should i write?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mr.novak
  • 15
  • 5
  • 2
    You can't reference `this` from a static method. Did you actually study the language first? – Chisko Feb 08 '18 at 16:39

3 Answers3

0

You need to pass reference of activity context like :-

public static void startNewAct(Context con) {
    Intent intent = new Intent(con, MainActivity2.class);
}
duggu
  • 37,851
  • 12
  • 116
  • 113
-1

You can do this

imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(getItemId() == 0){
                    Intent intent = new Intent(view.getContext(), Spacex.class);

                }
            }
        });
Napster
  • 1,353
  • 1
  • 9
  • 11
-1

You can use Intent.setClassName() which takes strings.

Intent intent = new Intent();
intent.setClassName("com.example", "./Activity");
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134