Android - make toast or dialog inside static inner class of activity -


i having problem getting application context inside static inner class:

public class mainactivity extends activity {         .....         ....          public static class smsalerthandler extends broadcastreceiver {                 @override                 public void onreceive(context context, intent intent) {                     ....                     ....                     toast.maketext(context, "this toast message!!! =)",                                toast.length_long).show();                     }                 }             } 

if give context giving exception

unable add window — token null not application

also if put getapplicationcontext(), showing error

cannot make static reference non-static method getapplicationcontext() type contextwrapper

yeap, static methods can't use references non-static fields. , context receive receiver not allowed make ui operations, can take in this article shows can each context received.

you can set receiver in activity, this:

protected void onresume() {     super.onresume();     intentfilter filter = new intentfilter("youraction");     registerreceiver(receiver, filter);     // or localbroadcastmanager.getinstance(this).registerreceiver(receiver, filter); if using localbroadcast system }     private broadcastreceiver receiver = new broadcastreceiver() {      @override      public void onreceive(context context, intent intent) {          toast.maketext(mainactivity.this, "message", lenght_long).show();      }  } 

and second approach (i'm not sure if work because didn't test yet) in resume context application class:

you can create application class context, example:

public class app extends android.app.application {      private static android.app.application application;      public static context getcontext() {         return application.getapplicationcontext();     }      public void oncreate() {         super.oncreate();         application = this;     } } 

then able use inside receiver:

public static class smsalerthandler extends broadcastreceiver {    @override    public void onreceive(context context, intent intent) {         toast.maketext(app.getcontext(), "this toast message!!! =)",                                toast.length_long).show();         }    } } 

remeber add app class androidmanifext.xml

<application         android:name=".app"         ... > 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -