calling method from my asynctask must be static - android

I'm not sure why it is but I cannot call a method in my asynctask that is not static.
protected void onPostExecute(String result) {
List<SingleEvent> thelist = PhotosActivity.parseJSONResponse(result);
PhotosActivity.refreshListView(thelist);
}
The method in my activity:
public void refreshListView(List<SingleEvent> theList){//method that adds the List to the ListView after asyncTask is finished.
SingleEventAdapter adapter = new SingleEventAdapter(this, theList);
this.list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
It says I should make my method static, but in doing so the code inside gets errors saying it cannot be used with static.
EDIT:
The following is my asynctask class:
public class CallWebServiceTask extends AsyncTask<String, Object, String> {}
it's not static?

You must do this (make sure your AsyncTask class is not static):
PhotosActivity.this.refreshListView(thelist);

Related

how check doinbackground(Void.. ar) method is completed in android

I am creating a program that fetch the value from online . I have use AsynTask class for background process. i am fetching the some values from web and set value in class variables.My problem is that values are setting in variables in very late. and my execution processed further and find variables values null. How can i check that doInBackground() method is processed completely and values are sets in variable. so that i can use these variables values.
One of the best method is to use a kind of observer design pattern.
So first create an Interface with contain a method (depend on your return value, etc) :
public interface OnTaskCompleted{
void onTaskCompleted(String xml);
}
Then you need to implement this interface to your activity wich instantiate your asynctack, see:
public class MainActivity extends SherlockFragmentActivity implements OnTaskCompleted
Then to finish, you gonna pass the instance of MainActivity (wich by polymorphisme is also OnTaskCompleted) to your asyntask. Here my asyntask class handler is named XMLParser
public class XMLParser {
private OnTaskCompleted listener;
public XMLParser(OnTaskCompleted mainActivity, String url){
getXMLFromURL(mainActivity,url);
}
[......]
//here when the work is done you call the OnTaskComplete Method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//CALL HERE
listener.onTaskCompleted(result);
}
}
I hope it'll help you. Works like a charm for me.

How to implement an AsyncTask pattern to avoid too verbose code

I'm implementing an app that uses many methods that requires an AsyncTask with a waiting dialog.
Actually my approach is to use every time an inner class that extends AsyncTask
something like
private class AsyncOperation extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(CurrencyConverterActivity.this);
pDialog.setMessage("Waiting...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
...
return null
}
protected void onPostExecute(Void params){
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
//dialogs according status the
//int status is a static variable declared in external class
}
});
}
since with this approach i have to write this inner class too many times and this result in dirty code not well readable, I'm looking for a smarter solution
Could someone help me?
Are you calling the same network each time you use the async task?
If yes, then you can have one class which extends the async and pass the values for each call. You can have response listener to get the response from the method called the async
Something like this:
MainActivity:
First method:
AsyncOperation asyncCall = new AsyncOperation(MainActivity.this, "abc", "bcd");
asyncCall.execute();
Second method:
AsyncOperation asyncCall = new AsyncOperation(MainActivity.this, "aaa", "bbb");
asyncCall.execute();
callback(…){
}
Async Class:
private class AsyncOperation extends AsyncTask<Void, Void, Void> {
AsyncOperation(listener, string, string)
{
}
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(CurrencyConverterActivity.this);
pDialog.setMessage("Waiting...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
...
return null
}
protected void onPostExecute(Void params){
pDialog.dismiss();
listener.callback(…);
}
You can create an AsyncTask in a separate file (not as an inner class) and reuse it many times. AsyncTask doesn't have to be an inner class.
You may need to modify your AsyncTask to take additional parameters if needed to make it reusable.
You can also create a constructor for your AsyncTask with parameters for the values you need to pass into it and use that constructor to instantiate your AsyncTask.
This approach makes sense if the way you use AsyncTasks in different places is the same or at least similar. If you use completely different code in each AsyncTask, you will be better off with separate AsyncTasks (though you may still extract them into separate classes from inner classes).

Activity -> AsyncTask -> BroadcastReceiver -> Update UI

I am starting an AsyncTask from an Activity. When, the AsyncTask completes its execution I need to send a broadcast which needs to call Activity method to update the UI.
Any good approach to achieve this.
Yes.
If the AsyncTask is an inner class of your Activity then it has access to any member variables and your Activity methods. If it isn't then you can simply pass variables to its constructor or even a reference to the Activity to call Activity methods from onPostExecute(). Without any code its hard to say much else.
To pass an instance of your Activity and use its methods if its a separate class then you can create a constructor and do something like
public class MyTask extends AsyncTask<...> // add your params
{
private MyActivity activty;
public MyTask (MyActivity act)
{
this.activty = activty;
}
// ...
}
and in onPostExecute() add something like
activity.myMethod();
and call the task like
MyTask task = new MyTask(this); // pass a reference of the activity
task.execute(); // add params if needed
If the AsyncTask is a separate file from the Activity then you can see this answer on how to use an interface for a callback
Please use Interface.
interface INotifyChange {
void notifyChange(); // You can use params to transfer data :D
}
In Activity you should implements this interface.
YourActivity extends Activity implements INotifyChange {
#Override
public void notifyChange() {
// Right here, you can Update UI.
}
}
When you create new instance of AsyncTask
Example:
YourAsyncTask mTask = new YourAsyncTask(this); // You put INotifyChange
In YourAsyncTask
private INotifyChange iNotifyChange;
public YourAsyncTask(INotifyChange iNotifyChange) {
this.iNotifyChange = iNotifyChange;
}
// When you complete doInBackground or anywhere you want to Update UI please use iNotifyChange.notifyChange()
Example:
#Override
public void onPostExecute(ResultType mResult) {
iNotifyChange.notifyChange();
}
By this way I often use to update progress bar. In this case, I use parameter in my method:
Example:
iNotifyChange.notify(progress);
Have you considered overwriting the onPostExecute() method of the AsyncTask to update the UI? Try something like this:
AsyncTask<String, Void, Bitmap> task = new AsyncTask<String, Void, Bitmap>(imageView)
{
private ImageView imageView;
public AsyncTask(ImageView imageView)
{
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground (String... params)
{
if(params.length > 0)
{
String filePath = params[0];
// Load Bitmap from file
return bitmap;
}
}
#Override
protected void onPostExecute(Bitmap result)
{
imageView.setImageBitmap(result);
}
}
task.execute(filePath);

how to pass the result of asynctask onpostexecute method into the parent activity android

I am developing an application in which i need to send the value of the asynctask's onPostExecute method's result in to the previous activity , ie the activity in which the aync task is being called.pls put some codes. Anyhelp is appreciated
Two ways:
Declare class extending AsyncTask as private class in parent Activity
Pass Handler or Activity itself as param of class extending AsyncTask
If I were you, I'd follow the first option.
Look at DOCS:
class MyActivitySubclass extends Activity {
function runOnPostExecute(){
// whatever
}
private class MyTask extends AsyncTask<Void, Void, Void> {
void doInBackground(Void... params){
// do your background stuff
}
void onPostExecute(Void... result){
runOnPostExecute();
}
}
}
Note 1
Code placed in body of function onPostExecute is already run on Activity thread, you should just mention that this keywords leads to MyTask.this and not MyActivitySubclass.this
Well if your AsyncTask is an inner class, you could simply call a method in your activity from onPostExecute():
public class MyActivity extends Activity {
public void someMethod(String someParam) {
// do something with string here
}
public class InnerTask extends AsyncTask<...> {
protected void onPostExecute(result) {
someMethod(Send parameters);
}
}
}
The onPostExecute method is fired on the main UI thread, so anything done there is already on the AsyncTasks caller.
http://developer.android.com/reference/android/os/AsyncTask.html
Fire an event in the OnPostExecute.
Its an add on to the answer by Marek Sebera, he pointed to use a handler. To keep the code simple and intuitive use an interface. This isn't alien concept, we use it all the time for callback functions (eg: OnClickListner etc..). The code would look some thing like this.
public class InnerTask extends AsyncTask<...>
{
interface ResultHandler
{
void gotResult(<> result);
}
private ResultHandler myResult;
//constructor
public InnerTask(....params...,ResultHandler callback)
{
...
this.myResult = callback;
}
protected void onPostExecute(<>result)
{
...
myResult.gotResult(result);
}
}
public class MyActivity extends Activity implements InnerTask.ResultHandler
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
//do something
//if you want the InnerTask to execute here
InnerTask i = new InnerTask(....params...,this); //send 'this' as parameter
i.execute();
}
#Override
public void gotResult(<> result)
{
//from onPostExecute
}
}
If we want to use the same AsynTask class at multiple sites we can use this type of implementation instead of using nested classes implementation.

Async Task Data fetcher

I have one class that extends Asynctask. In this class I have a method that returns a hash map. How can I get this Hashmap in different class that extends Activity.
Anyone give me some reference code?
You can create a listener in your Activity, then pass this listener into your AsyncTask. Once the AsyncTask completes you can call the listener to set the Hashmap. So in your AsyncTask create your listener:
public static interface MyListener {
void setHashmap(Hashmap myHashmap);
}
Also, have a function to set your listener:
public void setListener(MyListener listener) {
this.listener = listener;
}
Then in onPostExecute call the function on your listener
listener.setHashmap(myHashmap);
In your activity implement this listener:
public class MyActivity extends Activity implements MyListener { ...
public void setHashmap(Hashmap hashmap) {
// do stuff here
this.hash = hashmap
}
Then finally set your listener and start your AsyncTask:
AsyncTask task = new MyAsyncTask();
task.setListener(this);
task.execute();
Of course you could also just put your AsyncTask in your Activity then you can set the hashmap in onPostExecute.

Categories

Resources