Monday, June 9, 2014

Android - Static Access to Context outside of an Activity or Service

I recently got a crash report in my Android app (Megalarm, you should check it out) because the Context object in one of my singleton classes was stale and unexpectedly null. This is a Context object that was cached when the application was first launched at bootup.


To get around this, I started with a trick learned from this question on Stack Overflow.


(decorate your application node in AndroidManifest.xml as such)
<application android:name="com.seandroid.megalarm.MegalarmApplication">
    ...
</application>


(then create the matching application class)
public class MegalarmApplication extends Application
{
 private static Context initialContext;
 
 @Override
 public void onCreate()
 {
  super.onCreate();
  initialContext = getApplicationContext();
 }
 
 public static Context getAppContext()
 {
  return initialContext;
 }
}

This method of getting a Context object statically is good as it works most of the time but doesn't guarantee it won't be null (should getAppContext() be called before it has been created). Nonetheless this works in most cases.


However it doesn't fix my problem where the value was stale and null at one point much later. That's why I supplemented this with another class:

public class ContextHelper
{
 private static final ContextHelper instance;
 private Context latestContext;
 
 static
 {
  instance = new ContextHelper();
 }
 private ContextHelper()
 {}
 
 public static ContextHelper getInstance()
 {
  return instance;
 }
 
 public Context getContext()
 {
  if (latestContext != null)
   return latestContext;
  
  return MegalarmApplication.getAppContext();
 }
 public void setContext(Context ctxt)
 {
  latestContext = ctxt;
 }
}


This class will returned the latest Context object and if that is missing, the Context in the other singleton: MegalarmApplication.

Lastly, I modified my Activity classes on add a call to track the Context in each onResume() implementation.

@Override
protected void onResume()
{
 ...
 super.onResume();
 ContextHelper.getInstance().setContext(this);
}

I hope this helps you out if you've come across a similar problem.

52 comments:

  1. well said about Static Access to Context outside of an Activity or ServiceAndroid Training

    ReplyDelete
  2. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more Android Training

    ReplyDelete
  3. This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 
    java training in chennai | java training in bangalore

    java online training | java training in pune

    java training in chennai | java training in bangalore

    ReplyDelete
  4. All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.
    python training in tambaram
    python training in annanagar
    python training in OMR
    python training in chennai

    ReplyDelete
  5. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    Blueprism training in Bangalore

    Blueprism training in Pune

    Blueprism training in Chennai

    ReplyDelete
  6. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    ReplyDelete
  7. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  8. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  9. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training



    https://seblogapps.blogspot.com/2015/11/mit-app-inventor-multitouch-e-pinch-to.html

    ReplyDelete
  10. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  11. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  12. Informative post indeed, I’ve being in and out reading posts regularly and I see alot of engaging people sharing things and majority of the shared information is very valuable and so, here’s my fine read.
    click here to connect
    click here to check the status of your arn
    click here for citizen registration
    click here to continue your registration
    click here to confirm

    ReplyDelete
  13. Thanks for this article.You can visit my website :mp3 bee

    ReplyDelete
  14. Your article is very helpful.You can visit my website :flvto download

    ReplyDelete
  15. Subscription boxes are a type of boxes which are delivered to the regular customers in order to build goodwill of the brand. They are also a part of the product distribution strategy. As a woman, you should subscribe to these boxes to bless yourself with a new and astonishing box of happiness each month. visit mysubscriptionsboxes

    ReplyDelete
  16. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. Automation Anywhere Training in Bangalore

    ReplyDelete
  17. If Your are not ediot then try this app AIMP Apk

    ReplyDelete
  18. I have been using this app The Pirate: Caribbean Hunt Mod Apk : and downloaded and gambling it frequently.

    ReplyDelete
  19. Worth reading! Our experts also have given detailed inputs about these trainings & courses! Presenting here for your reference. Do checkout
    oracle sql training in chennai & enjoy learning more about it.

    ReplyDelete
  20. Study Hadoop for making your career as a shining sun with Infycle Technologies. Infycle Technologies offers the best Hadoop Training in Chennai, providing complete hands-on practical training of professional specialists in the field. In addition to that, it also offers numerous programming language tutors in the software industry such as Oracle, Python, Big Dat, Hadoop, etc. Once after the training, interviews will be arranged for the candidates, so that, they can set their career without any struggle. Of all that, 100% placement assurance will be given here. To have the top career in IT industry, dial 7502633633 to Infycle Technologies and grab a free demo to know more.

    ReplyDelete
  21. Did you want to set your career towards Oracle? Then Infycle is with you to make this into reality. Infycle Technologies offers the best Oracle DBA training in Chennai, which offers various stages of Oracle such as Oracle PL/SQL, etc., along with 100% hands-on training guided by experienced trainers in the field. Once after the training, the interviews will be arranged in the MNC's and firms for the placement. To have the Oracle with the best future, call 7502633633 and make this happen for your happy life.

    ReplyDelete
  22. If AWS is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best AWS Training in Chennai, with various levels of highly demanded software courses such as Oracle, Java, Python, Hadoop, Big Data, etc., in 100% hands-on practical training with specialized tutors in the field. Along with that, the pre-interviews will be given for the candidates, so that, they can face the interviews with complete knowledge. To know more, dial 7502633633 for more.

    Python training institute in Chennai

    ReplyDelete
  23. Grab the Digital Marketing Training in Chennai from Infycle Technologies, the best software training institute, and Placement center in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Cyber Security, Big Data, Java, Hadoop, Selenium, Android, and iOS Development, DevOps, Oracle etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

    ReplyDelete
  24. I see the greatest contents on your blog and I extremely love reading them.
    data scientist training in malaysia

    ReplyDelete
  25. If you are dreaming of an IT job !!! Then AWS Course in Chennai!!Is the best choice for you. Yes, what you heard is Right Infycle offering you an AWS course for an Affordable price with experienced trainees, Practical Classes, Flexible timing, and more.

    ReplyDelete
  26. This post is so interactive and informative.keep update more information...
    Java Training in Tambaram
    java course in tambaram

    ReplyDelete