1

I tried to put context in my static method as below :

public class Menu_SPPAJ extends Activity {
public static void onRefreshList() {
     model.requery();
     list_terbaru.setAdapter(new Adapter_Spaj_Terbaru(Menu_SPPAJ.this,model));
}
}

but Menu_SPPAJ.this is undefined in static method, is there anyway how to call my context in static method?

Menma
  • 799
  • 1
  • 9
  • 35

6 Answers6

2

You can pass a context as an argument.

Though it looks like your method should not be static as it is accessing variables that look like member variables.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • The same alternative is used by many and I too use this option :) – codeRider Apr 08 '14 at 07:40
  • @laalto well, i need to make it static, because I will call this method from another class, can you show me thow to pass a context as an argument? – Menma Apr 08 '14 at 07:40
  • You don't need methods to be static to call them from other classes. You just need to pass an object reference around to call the methods on. Making things static like this causes more problems than it solves. – laalto Apr 08 '14 at 07:45
2

You can pass one parameter as context, like this

public static void show (Context context){
    Toast.makeText(context, "testing toast", Toast.LENGTH_LONG).show();
}
Krunal Indrodiya
  • 782
  • 2
  • 7
  • 19
1
Use this code for context in static method.

public class Menu_SPPAJ extends Activity {
public static Context context;
    @Override
    public void onCreate(Bundle savedInstanceState) {
       //TODO write your onCreate code
        context = this;
    }
public static void onRefreshList() {
     model.requery();
     list_terbaru.setAdapter(new Adapter_Spaj_Terbaru(((Activity) context),model));
}
}
YasirSE
  • 161
  • 1
  • 10
1

You change your static method like this,

public static void onRefreshList(Context context) {
model.requery();
list_terbaru.setAdapter(new Adapter_Spaj_Terbaru(context,model));

}

Suhas K
  • 74
  • 8
0

You could simply use the Singleton Pattern. If you implement that pattern you can use all nonstatic functionality on the inside of your class and still have static-like behavior to the outside.

Yannic Welle
  • 207
  • 2
  • 10
0
public class Menu_SPPAJ extends Activity {

public static void onRefreshList(Context context) {
 model.requery();
 list_terbaru.setAdapter(new Adapter_Spaj_Terbaru(context,model));
}

// if you are calling this method from on create then

onCreate(){

onRefreshList(this);
}
}
Amit
  • 391
  • 3
  • 15