Calling methods on a weak reference object









up vote
0
down vote

favorite












I had created a static variable to save app context since I was going to use it at other places in the class. This variable was getting assigned in the constructor of the class and I was getting the following error - "Do not place Android context classes in static fields (static reference to MyClass which has field appContext pointing to Context); this is a memory leak (and also breaks Instant Run) [StaticFieldLeak]"



Below is the code within MyClass:



private static Context appContext;
public MyClass(Context context)
appContext = context;



To fix this issue I thought of making appContext as a weak reference variable. But I am unable to call any methods on that variable because it's of weak reference. Below is the updated code and the error I get while I tried to call a method on weak object.



Updated code:



private final WeakReference<Context> appContext;
public MyClass(Context context)
appContext = new WeakReference<Context>(context);



At some places in my class am trying to call appContext.getPackageManager() and appContext.getString() and I am seeing below errors:



error: cannot find symbol
symbol: method getPackageManager()
location: variable appContext of type WeakReference<Context>

error: cannot find symbol
symbol: method getString(int)
location: variable appContext of type WeakReference<Context>


How can I fix the memory leak issue if I don't make the variable a weak reference? Or if I make a weak reference, how do I execute methods on it?










share|improve this question



























    up vote
    0
    down vote

    favorite












    I had created a static variable to save app context since I was going to use it at other places in the class. This variable was getting assigned in the constructor of the class and I was getting the following error - "Do not place Android context classes in static fields (static reference to MyClass which has field appContext pointing to Context); this is a memory leak (and also breaks Instant Run) [StaticFieldLeak]"



    Below is the code within MyClass:



    private static Context appContext;
    public MyClass(Context context)
    appContext = context;



    To fix this issue I thought of making appContext as a weak reference variable. But I am unable to call any methods on that variable because it's of weak reference. Below is the updated code and the error I get while I tried to call a method on weak object.



    Updated code:



    private final WeakReference<Context> appContext;
    public MyClass(Context context)
    appContext = new WeakReference<Context>(context);



    At some places in my class am trying to call appContext.getPackageManager() and appContext.getString() and I am seeing below errors:



    error: cannot find symbol
    symbol: method getPackageManager()
    location: variable appContext of type WeakReference<Context>

    error: cannot find symbol
    symbol: method getString(int)
    location: variable appContext of type WeakReference<Context>


    How can I fix the memory leak issue if I don't make the variable a weak reference? Or if I make a weak reference, how do I execute methods on it?










    share|improve this question

























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I had created a static variable to save app context since I was going to use it at other places in the class. This variable was getting assigned in the constructor of the class and I was getting the following error - "Do not place Android context classes in static fields (static reference to MyClass which has field appContext pointing to Context); this is a memory leak (and also breaks Instant Run) [StaticFieldLeak]"



      Below is the code within MyClass:



      private static Context appContext;
      public MyClass(Context context)
      appContext = context;



      To fix this issue I thought of making appContext as a weak reference variable. But I am unable to call any methods on that variable because it's of weak reference. Below is the updated code and the error I get while I tried to call a method on weak object.



      Updated code:



      private final WeakReference<Context> appContext;
      public MyClass(Context context)
      appContext = new WeakReference<Context>(context);



      At some places in my class am trying to call appContext.getPackageManager() and appContext.getString() and I am seeing below errors:



      error: cannot find symbol
      symbol: method getPackageManager()
      location: variable appContext of type WeakReference<Context>

      error: cannot find symbol
      symbol: method getString(int)
      location: variable appContext of type WeakReference<Context>


      How can I fix the memory leak issue if I don't make the variable a weak reference? Or if I make a weak reference, how do I execute methods on it?










      share|improve this question















      I had created a static variable to save app context since I was going to use it at other places in the class. This variable was getting assigned in the constructor of the class and I was getting the following error - "Do not place Android context classes in static fields (static reference to MyClass which has field appContext pointing to Context); this is a memory leak (and also breaks Instant Run) [StaticFieldLeak]"



      Below is the code within MyClass:



      private static Context appContext;
      public MyClass(Context context)
      appContext = context;



      To fix this issue I thought of making appContext as a weak reference variable. But I am unable to call any methods on that variable because it's of weak reference. Below is the updated code and the error I get while I tried to call a method on weak object.



      Updated code:



      private final WeakReference<Context> appContext;
      public MyClass(Context context)
      appContext = new WeakReference<Context>(context);



      At some places in my class am trying to call appContext.getPackageManager() and appContext.getString() and I am seeing below errors:



      error: cannot find symbol
      symbol: method getPackageManager()
      location: variable appContext of type WeakReference<Context>

      error: cannot find symbol
      symbol: method getString(int)
      location: variable appContext of type WeakReference<Context>


      How can I fix the memory leak issue if I don't make the variable a weak reference? Or if I make a weak reference, how do I execute methods on it?







      java android weak-references






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 at 17:11









      Kling Klang

      32.3k156288




      32.3k156288










      asked Nov 9 at 16:15









      tech_human

      2,393104274




      2,393104274






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          You need to call the get() method on the WeakReference<Context> in order to extrapolate the Context value.



          WeakReference<Context> has no getPackageManager() method, that's why you're getting that error.






          share|improve this answer



























            up vote
            0
            down vote













            The whole "context" thing really makes it hard to do layering in Android.

            Without seeing the class you are trying to access, it is hard to say for certain but one option is to make all the functions static and call them with the context from your other classes. You can pass context to a static function and use it within, you just can't save it to a static variable. For example:



            static void doStuff(Context context)
            //do context stuff

            MyClass.doStuff(myCurrentClass.this);


            If you instantiating the class as an object, you don't even need to make the global context variable static at all.






            share|improve this answer




















            • You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
              – Luca Nicoletti
              Nov 10 at 9:51










            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229448%2fcalling-methods-on-a-weak-reference-object%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            You need to call the get() method on the WeakReference<Context> in order to extrapolate the Context value.



            WeakReference<Context> has no getPackageManager() method, that's why you're getting that error.






            share|improve this answer
























              up vote
              0
              down vote



              accepted










              You need to call the get() method on the WeakReference<Context> in order to extrapolate the Context value.



              WeakReference<Context> has no getPackageManager() method, that's why you're getting that error.






              share|improve this answer






















                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                You need to call the get() method on the WeakReference<Context> in order to extrapolate the Context value.



                WeakReference<Context> has no getPackageManager() method, that's why you're getting that error.






                share|improve this answer












                You need to call the get() method on the WeakReference<Context> in order to extrapolate the Context value.



                WeakReference<Context> has no getPackageManager() method, that's why you're getting that error.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 9 at 16:24









                Luca Nicoletti

                1,20221022




                1,20221022






















                    up vote
                    0
                    down vote













                    The whole "context" thing really makes it hard to do layering in Android.

                    Without seeing the class you are trying to access, it is hard to say for certain but one option is to make all the functions static and call them with the context from your other classes. You can pass context to a static function and use it within, you just can't save it to a static variable. For example:



                    static void doStuff(Context context)
                    //do context stuff

                    MyClass.doStuff(myCurrentClass.this);


                    If you instantiating the class as an object, you don't even need to make the global context variable static at all.






                    share|improve this answer




















                    • You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
                      – Luca Nicoletti
                      Nov 10 at 9:51














                    up vote
                    0
                    down vote













                    The whole "context" thing really makes it hard to do layering in Android.

                    Without seeing the class you are trying to access, it is hard to say for certain but one option is to make all the functions static and call them with the context from your other classes. You can pass context to a static function and use it within, you just can't save it to a static variable. For example:



                    static void doStuff(Context context)
                    //do context stuff

                    MyClass.doStuff(myCurrentClass.this);


                    If you instantiating the class as an object, you don't even need to make the global context variable static at all.






                    share|improve this answer




















                    • You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
                      – Luca Nicoletti
                      Nov 10 at 9:51












                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    The whole "context" thing really makes it hard to do layering in Android.

                    Without seeing the class you are trying to access, it is hard to say for certain but one option is to make all the functions static and call them with the context from your other classes. You can pass context to a static function and use it within, you just can't save it to a static variable. For example:



                    static void doStuff(Context context)
                    //do context stuff

                    MyClass.doStuff(myCurrentClass.this);


                    If you instantiating the class as an object, you don't even need to make the global context variable static at all.






                    share|improve this answer












                    The whole "context" thing really makes it hard to do layering in Android.

                    Without seeing the class you are trying to access, it is hard to say for certain but one option is to make all the functions static and call them with the context from your other classes. You can pass context to a static function and use it within, you just can't save it to a static variable. For example:



                    static void doStuff(Context context)
                    //do context stuff

                    MyClass.doStuff(myCurrentClass.this);


                    If you instantiating the class as an object, you don't even need to make the global context variable static at all.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 9 at 16:26









                    Notsileous

                    22818




                    22818











                    • You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
                      – Luca Nicoletti
                      Nov 10 at 9:51
















                    • You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
                      – Luca Nicoletti
                      Nov 10 at 9:51















                    You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
                    – Luca Nicoletti
                    Nov 10 at 9:51




                    You completely misunderstood what he wanted to achieve. And your suggestion is pretty bad. Context in Android is a super object, has too much power in it and should not be passed wherever only a part of it is supposed to be needed. If, for example, you need resources, just pass resources and not the entire context
                    – Luca Nicoletti
                    Nov 10 at 9:51

















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229448%2fcalling-methods-on-a-weak-reference-object%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                    Crossroads (UK TV series)

                    ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế