Menma
Menma

Reputation: 809

android context in static method is undefined

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?

Upvotes: 1

Views: 575

Answers (6)

Amit
Amit

Reputation: 381

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);
}
}

Upvotes: 0

Yannic Welle
Yannic Welle

Reputation: 207

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.

Upvotes: 0

Suhas K
Suhas K

Reputation: 74

You change your static method like this,

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

}

Upvotes: 1

YasirSE
YasirSE

Reputation: 161

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));
}
}

Upvotes: 1

Krunal Indrodiya
Krunal Indrodiya

Reputation: 792

You can pass one parameter as context, like this

public static void show (Context context){
    Toast.makeText(context, "testing toast", Toast.LENGTH_LONG).show();
}

Upvotes: 2

laalto
laalto

Reputation: 152817

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.

Upvotes: 2

Related Questions