Android: Get context of working activity at the time - android

Is there a method to return the working activity's context?
I started a process in the background, that need to make a toast in the middle of its execution, I need to have the current context so the toast can take it. The problem is I don't know exactly in what activity the user could be at the time the async task create the toast.
Any help please?

I need to have the current context so the toast can take it.
Application context of your app is sufficient for Toast to show. You do not need Activity's context (and Activity is subclass of Context btw) for this.

Related

unable to make toast in activity constructor

I am getting an error as Null pointer exception and unable to instantiate activity when I am creating a toast in activity constructor.I want to know the reason why toasts are working in onCreate method but not in activity constructor
The OS is responsible for constructing your Activity classes. This is because it needs to perform some setup, including providing the Activity a proper base Context. Without this, you cannot make Toasts.
In general, you should avoid doing anything in the constructor of an Activity (and you should definitely not be making instances of them yourself using new).
Usually a Toast appears as a feedback to user input (say a button click) or when some external event is registerd (say a network error happend or new incoming data is available).
However, to me it sounds as though you want to show a Toast right after opening your activity, is that correct? Then you should put it in the onCreate method of your activity. An example Toast is made like this
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_LONG).show();
You might also consider putting this call in the onResume method. I recommend getting familiar with activity lifecycles.
Instead of using Toasts you might also want to check out Snackbars.

Using context reference after activity be finished

I have a complete button in page, when user click button, it will start an async task and pass the activity context into it, then finish the activity to dismiss the activity view.
What will happen if the activity be finished but the background task still need to use the context reference passed in? will it have any concerns? or have alternative/better way for this kind of situation.
any suggestions will be appreciated!
First of all, in this situation you better go for service instead of asynctask. In your case, Service should stop itself once task is finished.
Even if you go for asynctask, try to use application context that you can get from activity context as below:
activity_context.getApplicationContext();
The application context will be there even if activity is finished and also it will avoid memory leak.
And if you want to make the asynctask run safely even if activity is finished, then try not to update any UI in postExecute(..) method as it will run on the UI of the activity which is already finished leading to exception. Try to do only any background task inside doInBackground(...) which runs on different thread.
Hope this answers your question.

Showing aler diaog box in async task which is outside the activity (after execution is completed )

I want to show the alertdialogbox in the async task onpostExecute method which is a differnt class and not written as an inner class. I am currently passing the activity in the async task constructor and using its context in the alerdialog but the application is crashing. Kindly help how it can be achieved.
Attached is the error I am getting, From the error I thought the I will have to use the handler as i am updating the UI so I added handler and put the alerbox inside it. but this way the application doesnt crash but also doesnt show the aletbox. The handler should not be used as I have read that the onpostExecute is called in the UI thread. Kindly tell me if I am wrong.
Thanks in advance.
You need to use the Activity Context instead of Application Context. You think this is what you are doing here
AlertDialog.Builder builder = new AlertDialog.Builder(imageUploadMainActivity.getApplicationContext());
but you are still calling getApplicationContext() which , guess what, returns the Application Context ;)
Instead us
AlertDialog.Builder builder = new AlertDialog.Builder(imageUploadMainActivity);
Assuming that imageUploadMainActivity is the variable which references the Context you passed to the AsyncTask. But, since you haven't shown that code, I can't say for sure.

progressdialog and context - window leaked

I am currently trying to define a seperate class for displaying ProgressDialogs as i dont want to create individual progressDialog instances in each and every activity. And i m currently sending the current activities context to that method. Things seems to work fine but at times (very random) it leads to a exception stating window Leaked. I even know that window leak occurs if i m trying to show dialog on a context which is finished. And i think the issue here could be because of some other part of code which is finishing my context before my dialog is shown.so i just want to make sure my method doesn't show the dialog if there is any issue with context.
Is there any way i can know whether my passed context is currently visible on the screen or not so that i will not run into these window leaked exceptions.
And also tried replacing the context with getApplicationContext(). but the progress dialog is not shown at all with this change.
Any help would be greatly appreciated.
Thank you all in advance
Dismiss the dialog in onPause() method .

When to use a service in Android

I have a class that fetches data in response to button presses in the main activity. Unfortunately, I keep running into problems because this class is not an Activity or a Service. For example, without a Context I cannot translate a resource id into a string:
getString(R.string.example_string); // Doesn't work
Should I make this class into a Service and have the main Activity stop the class when it is closed? Should I pass the Context from the Activity into this class like this?
MyClass c = new MyClass(this);
Or is there some better way to handle this problem?
This issue also comes up when I try to send a Toast from this class.
Update: Erich and Janusz pointed me in the direction of the AsyncTask class which works perfectly, except that it creates a new thread and never kills that thread. This means that ever time the user presses a button, another thread is added and the old ones just sit there.
If you have a background action whose lifecycle is decoupled from your activity, I would use a Service. In that case, the Service will have its own Context, so you won't need to pass it in. If, however, you need to perform a background action in response to a UI event (and optionally post the results back into the UI thread), I would recommend you use an AsyncTask.
I agree with Erich, if you only have a something small like posting a change to a web backend or loading something from the phone memory to show it on screen use a Async Task. If the task will exit very "quick" (some seconds) you can make an anonymous class inside your activity. This will enable you to use a implicit reference to the outer activity inside the task and you can get your context from there.
If the task is running for a longer time you can pass down the context. If you are passing down the context try to not pass this from the activity use this.getApplicationContext() this will minimize the number of references to your activity and enable the garbage collector to clean up properly.

Categories

Resources