android WeakReference of activity The 2019 Stack Overflow Developer Survey Results Are InIs there a way to run Python on Android?How do save an Android Activity state using save instance state?What's the difference between SoftReference and WeakReference in Java?Activity restart on rotation AndroidClose/hide the Android Soft KeyboardWhy is the Android emulator so slow? How can we speed up the Android emulator?Stop EditText from gaining focus at Activity startupIs there a unique Android device ID?What is 'Context' on Android?Proper use cases for Android UserManager.isUserAGoat()?

Ubuntu Server install with full GUI

Is it safe to harvest rainwater that fell on solar panels?

How did passengers keep warm on sail ships?

A female thief is not sold to make restitution -- so what happens instead?

Match Roman Numerals

What does Linus Torvalds mean when he says that Git "never ever" tracks a file?

How to obtain a position of last non-zero element

What is this sharp, curved notch on my knife for?

How do I free up internal storage if I don't have any apps downloaded?

How can I define good in a religion that claims no moral authority?

A word that means fill it to the required quantity

Short story: man watches girlfriend's spaceship entering a 'black hole' (?) forever

Can there be female White Walkers?

Why not take a picture of a closer black hole?

Can an undergraduate be advised by a professor who is very far away?

Can a flute soloist sit?

How to translate "being like"?

Why couldn't they take pictures of a closer black hole?

Why “相同意思的词” is called “同义词” instead of "同意词"?

"as much details as you can remember"

Geography at the pixel level

How to charge AirPods to keep battery healthy?

Correct punctuation for showing a character's confusion

Can we generate random numbers using irrational numbers like π and e?



android WeakReference of activity



The 2019 Stack Overflow Developer Survey Results Are InIs there a way to run Python on Android?How do save an Android Activity state using save instance state?What's the difference between SoftReference and WeakReference in Java?Activity restart on rotation AndroidClose/hide the Android Soft KeyboardWhy is the Android emulator so slow? How can we speed up the Android emulator?Stop EditText from gaining focus at Activity startupIs there a unique Android device ID?What is 'Context' on Android?Proper use cases for Android UserManager.isUserAGoat()?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have an Async Task, where I had a warning that it should be static or leaks might occur.



So I used a WeakReference like this:



 private static class GetContacts extends AsyncTask<String, Void, Boolean> 
ProgressDialog dialog;
private WeakReference<Novinky> activityReference;

GetContacts(Novinky context)
activityReference = new WeakReference<>(context);


@Override
protected void onPreExecute()

@Override
protected Boolean doInBackground(String... args)
HttpHandler sh = new HttpHandler();
String url = "https://www...";
String jsonStr = sh.makeServiceCall(url);

if (jsonStr != null)
try JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");

for (int i = 0; i < actors.length(); i++)
JSONObject c = actors.getJSONObject(i);

Actors actor = new Actors();

actor.setLetter(c.getString("letter"));
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("perex"));

actorsList.add(actor);


catch (final JSONException e)
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba dát: " + e.getMessage(),
Toast.LENGTH_LONG).show();

);

return true;

else
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();

);
return false;



protected void onPostExecute(Boolean result)



Now that warning is gone, but I am still fighting with some other errors which came up due my changes.



1/ actorsList.add(actor); - in my for loop now says Non-static field 'actorsList' cannot be referenced from a static context



2/ in catch and else statement where runOnUiThread is placed I have issues with Novinky.this.runOnUiThread - cannot be referenced from a static context



If I simply replace Novinky.this with the WeakReference (activityReference) then it says class name is expected, so not sure how to correctly replace Novinky.this in those threads.



I tried also to use Novinky activity = activityReference.get(); and then use activity.runOnUiThread - this removes the error, but the definition of Novinky activity = activityReference.get(); has then warning This field leaks a context object



3/ The last issue is in my onPostExecute - adapter.notifyDataSetChanged();. The error says: Non-static field 'adapter' cannot be referenced from a static context



UPDATE: I solved it somehow and now I have no errors and the app is running, however still not sure if I solved it correctly:



For 1/ I defined static ArrayList<Actors> actorsList; in the main class.



2/ in catch and else I defined
final Novinky activity = activityReference.get();



and then:



activity.runOnUiThread



3/ in onPostExecute I used activity.adapter.notifyDataSetChanged();










share|improve this question
























  • should have accepted the array list in the constructor of your AsyncTask class.

    – mudit_sen
    Mar 8 at 11:07

















0















I have an Async Task, where I had a warning that it should be static or leaks might occur.



So I used a WeakReference like this:



 private static class GetContacts extends AsyncTask<String, Void, Boolean> 
ProgressDialog dialog;
private WeakReference<Novinky> activityReference;

GetContacts(Novinky context)
activityReference = new WeakReference<>(context);


@Override
protected void onPreExecute()

@Override
protected Boolean doInBackground(String... args)
HttpHandler sh = new HttpHandler();
String url = "https://www...";
String jsonStr = sh.makeServiceCall(url);

if (jsonStr != null)
try JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");

for (int i = 0; i < actors.length(); i++)
JSONObject c = actors.getJSONObject(i);

Actors actor = new Actors();

actor.setLetter(c.getString("letter"));
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("perex"));

actorsList.add(actor);


catch (final JSONException e)
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba dát: " + e.getMessage(),
Toast.LENGTH_LONG).show();

);

return true;

else
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();

);
return false;



protected void onPostExecute(Boolean result)



Now that warning is gone, but I am still fighting with some other errors which came up due my changes.



1/ actorsList.add(actor); - in my for loop now says Non-static field 'actorsList' cannot be referenced from a static context



2/ in catch and else statement where runOnUiThread is placed I have issues with Novinky.this.runOnUiThread - cannot be referenced from a static context



If I simply replace Novinky.this with the WeakReference (activityReference) then it says class name is expected, so not sure how to correctly replace Novinky.this in those threads.



I tried also to use Novinky activity = activityReference.get(); and then use activity.runOnUiThread - this removes the error, but the definition of Novinky activity = activityReference.get(); has then warning This field leaks a context object



3/ The last issue is in my onPostExecute - adapter.notifyDataSetChanged();. The error says: Non-static field 'adapter' cannot be referenced from a static context



UPDATE: I solved it somehow and now I have no errors and the app is running, however still not sure if I solved it correctly:



For 1/ I defined static ArrayList<Actors> actorsList; in the main class.



2/ in catch and else I defined
final Novinky activity = activityReference.get();



and then:



activity.runOnUiThread



3/ in onPostExecute I used activity.adapter.notifyDataSetChanged();










share|improve this question
























  • should have accepted the array list in the constructor of your AsyncTask class.

    – mudit_sen
    Mar 8 at 11:07













0












0








0








I have an Async Task, where I had a warning that it should be static or leaks might occur.



So I used a WeakReference like this:



 private static class GetContacts extends AsyncTask<String, Void, Boolean> 
ProgressDialog dialog;
private WeakReference<Novinky> activityReference;

GetContacts(Novinky context)
activityReference = new WeakReference<>(context);


@Override
protected void onPreExecute()

@Override
protected Boolean doInBackground(String... args)
HttpHandler sh = new HttpHandler();
String url = "https://www...";
String jsonStr = sh.makeServiceCall(url);

if (jsonStr != null)
try JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");

for (int i = 0; i < actors.length(); i++)
JSONObject c = actors.getJSONObject(i);

Actors actor = new Actors();

actor.setLetter(c.getString("letter"));
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("perex"));

actorsList.add(actor);


catch (final JSONException e)
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba dát: " + e.getMessage(),
Toast.LENGTH_LONG).show();

);

return true;

else
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();

);
return false;



protected void onPostExecute(Boolean result)



Now that warning is gone, but I am still fighting with some other errors which came up due my changes.



1/ actorsList.add(actor); - in my for loop now says Non-static field 'actorsList' cannot be referenced from a static context



2/ in catch and else statement where runOnUiThread is placed I have issues with Novinky.this.runOnUiThread - cannot be referenced from a static context



If I simply replace Novinky.this with the WeakReference (activityReference) then it says class name is expected, so not sure how to correctly replace Novinky.this in those threads.



I tried also to use Novinky activity = activityReference.get(); and then use activity.runOnUiThread - this removes the error, but the definition of Novinky activity = activityReference.get(); has then warning This field leaks a context object



3/ The last issue is in my onPostExecute - adapter.notifyDataSetChanged();. The error says: Non-static field 'adapter' cannot be referenced from a static context



UPDATE: I solved it somehow and now I have no errors and the app is running, however still not sure if I solved it correctly:



For 1/ I defined static ArrayList<Actors> actorsList; in the main class.



2/ in catch and else I defined
final Novinky activity = activityReference.get();



and then:



activity.runOnUiThread



3/ in onPostExecute I used activity.adapter.notifyDataSetChanged();










share|improve this question
















I have an Async Task, where I had a warning that it should be static or leaks might occur.



So I used a WeakReference like this:



 private static class GetContacts extends AsyncTask<String, Void, Boolean> 
ProgressDialog dialog;
private WeakReference<Novinky> activityReference;

GetContacts(Novinky context)
activityReference = new WeakReference<>(context);


@Override
protected void onPreExecute()

@Override
protected Boolean doInBackground(String... args)
HttpHandler sh = new HttpHandler();
String url = "https://www...";
String jsonStr = sh.makeServiceCall(url);

if (jsonStr != null)
try JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");

for (int i = 0; i < actors.length(); i++)
JSONObject c = actors.getJSONObject(i);

Actors actor = new Actors();

actor.setLetter(c.getString("letter"));
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("perex"));

actorsList.add(actor);


catch (final JSONException e)
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba dát: " + e.getMessage(),
Toast.LENGTH_LONG).show();

);

return true;

else
Novinky.this.runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();

);
return false;



protected void onPostExecute(Boolean result)



Now that warning is gone, but I am still fighting with some other errors which came up due my changes.



1/ actorsList.add(actor); - in my for loop now says Non-static field 'actorsList' cannot be referenced from a static context



2/ in catch and else statement where runOnUiThread is placed I have issues with Novinky.this.runOnUiThread - cannot be referenced from a static context



If I simply replace Novinky.this with the WeakReference (activityReference) then it says class name is expected, so not sure how to correctly replace Novinky.this in those threads.



I tried also to use Novinky activity = activityReference.get(); and then use activity.runOnUiThread - this removes the error, but the definition of Novinky activity = activityReference.get(); has then warning This field leaks a context object



3/ The last issue is in my onPostExecute - adapter.notifyDataSetChanged();. The error says: Non-static field 'adapter' cannot be referenced from a static context



UPDATE: I solved it somehow and now I have no errors and the app is running, however still not sure if I solved it correctly:



For 1/ I defined static ArrayList<Actors> actorsList; in the main class.



2/ in catch and else I defined
final Novinky activity = activityReference.get();



and then:



activity.runOnUiThread



3/ in onPostExecute I used activity.adapter.notifyDataSetChanged();







android android-asynctask weak-references






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 10:42







wotan

















asked Mar 8 at 9:49









wotanwotan

18512




18512












  • should have accepted the array list in the constructor of your AsyncTask class.

    – mudit_sen
    Mar 8 at 11:07

















  • should have accepted the array list in the constructor of your AsyncTask class.

    – mudit_sen
    Mar 8 at 11:07
















should have accepted the array list in the constructor of your AsyncTask class.

– mudit_sen
Mar 8 at 11:07





should have accepted the array list in the constructor of your AsyncTask class.

– mudit_sen
Mar 8 at 11:07












1 Answer
1






active

oldest

votes


















1














You should be able to access your instance of the list the same way you access the adapter:



activityReference.get().actorsList





share|improve this answer























  • I removed the static definition and used activityReference.get().actorsList. Thank you

    – wotan
    Mar 8 at 12:13











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',
autoActivateHeartbeat: false,
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%2f55060595%2fandroid-weakreference-of-activity%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You should be able to access your instance of the list the same way you access the adapter:



activityReference.get().actorsList





share|improve this answer























  • I removed the static definition and used activityReference.get().actorsList. Thank you

    – wotan
    Mar 8 at 12:13















1














You should be able to access your instance of the list the same way you access the adapter:



activityReference.get().actorsList





share|improve this answer























  • I removed the static definition and used activityReference.get().actorsList. Thank you

    – wotan
    Mar 8 at 12:13













1












1








1







You should be able to access your instance of the list the same way you access the adapter:



activityReference.get().actorsList





share|improve this answer













You should be able to access your instance of the list the same way you access the adapter:



activityReference.get().actorsList






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 11:16









ry.ry.

466




466












  • I removed the static definition and used activityReference.get().actorsList. Thank you

    – wotan
    Mar 8 at 12:13

















  • I removed the static definition and used activityReference.get().actorsList. Thank you

    – wotan
    Mar 8 at 12:13
















I removed the static definition and used activityReference.get().actorsList. Thank you

– wotan
Mar 8 at 12:13





I removed the static definition and used activityReference.get().actorsList. Thank you

– wotan
Mar 8 at 12:13



















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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55060595%2fandroid-weakreference-of-activity%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

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved