How to use the managed query efficiently in Android? - android

I was trying to use the managedquery() in android to get back a cursor when working with a content provider. I used this because it was mentioned that this will handle the closing of the cursor by itself when the activity is paused or resumed.
But however this works on the Activity class only. But I have more than one background threads using the asynctask in android. I do a same fetch of list in more than one thread. So its repetitive code. This is because i cant call a function of one thread class from other thread dobackground(). Is there a easy and safe way to avoid this repetitive code. Kindly advice. Thank you for your help and time.

Can't you have an abstract asynctask class which implements this db query code (if that's all you're doing in the background thread, then put it in doInBackground(), otherwise put it in a private method), and then have your concrete child classes which extend this abstract class call super.doInBackground or call that private method?
E.G.
private abstract AbstractQueryTask extends AsyncTask<Long, Void, Long> {
protected Cursor querycode{
//put your query code here
}
}
public ConcreteQueryTask extends AbstractQueryTask {
//put the doInBackground and onPostExecute implementations here
}

Related

Can not Use Async Class inside an Activity . The Activity already Consist of a Main class extending from Activity

public class Server_Activity extends AsyncTask<Void, String, Void> {
}
An error is shown when I write this class:
ClassServer_Activity must either be declared abstract or implement abstract method doInBackground(params).
What is causing this error ?
Add the method doInBackground(). This is because the AsyncTask is an abstract class, which also contains the abstract method doInBackground(). This means, that any class inheriting from the AsyncTask class must also implement the doInBackground() method.
But your title seems to be another question, sounding like you wrote your Server_Activity class in the same file of another activity. in Eclipse this error would sound like:
The public type Testclass must be defined in its own file
If this is the case: Create a new .java file and write there your Server_Activity class.
And don't forget to implement the doInBackground() method there.
You can see an example of this in the android developer api.
implements doInBackground method in your code. Press ctrl+i, choose doInBackground and then enter to make it easy
based on the documentation you have to implement doInBackground. as doInbackground method is declared as abstract.
see documentations
http://developer.android.com/reference/android/os/AsyncTask.html
protected abstract Result doInBackground (Params... params)
Added in API level 3 Override this method to perform a computation on
a background thread. The specified parameters are the parameters
passed to execute(Params...) by the caller of this task. This method
can call publishProgress(Progress...) to publish updates on the UI
thread.
Parameters params The parameters of the task. Returns A result,
defined by the subclass of this task.
in your case Params... params is Void
↳ android.os.AsyncTask

Accesing AsyncTask form adapter class (non activity class)

I created AsyncTask in my Activity class it is working fine.My question is I have to access the same AsyncTask from adapter class how can i do this.Please provide any solutions.
Thanks in Advance.....
Create a separate class for your AsyncTask like below
File: DownloadFilesTask.java
public class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
---
---
}
}
In your activity, initialize object of your AsyncTask and execute it if required. You can do the same in your adapter class.
Please note that, according to threading rules, The AsyncTask class must be loaded on the UI thread and The task instance must be created on the UI thread. To work around this, just initialize object of AsyncTask on your activity's onCreate method (whether you are planning to use it in your activity or not, but it is necessary to create an object of AsyncTask if you want to use it outside your activity)

nested Activity class and AsyncTask

I post here because I have a difficult question.
I have a class that extends TabNewsActivity of Activity
This class contains a nested class TabNewsActivity: DownloadData which extends to AsyncTask >>
This class TabNewsActivity displays the recovered data from my web service, a spot DownloadData is asynchronous which allows me to retrieve the values ​​of my web service in a list.
To perform an update values ​​(in my application => refresh) I have to do this:
DownloadData (). Execute ();
But I can not do it out of my context TabNewsActivity: s
I would like a way to re execute this command, but in another tab for example.
Thank you for your help
Suggest making your DownloadData subclass in a separate class file, not a nested class of TabNewsActivity. You can pass it a Handler to act as a completion callback perhaps. This way you can execute DownloadData from TabNewsActivity, and pass it a Handler to call in TabNewsActivity upon completion. The same could hold true when calling it from another class.
AsyncTask execute() method is static so you dont need an instance of anything to call it. You call it like this:
AsyncTask.execute();
That will run what you have in your doInBackground() method. As far as I know you should be able to call AsyncTask.execute() anywhere in your app as long as you import AsyncTask.
Use AsyncTask inside of a Service.

Android Async Task dealing with UI

I am new to android development. I would like to accomplish a task described as follows:
A main activty which calls external class(the other class would extend AsyncTask) to parse xml and receive json by requesting to web service and starts a ProgressDialog.
The class performs xml and json parsing in its doInBackground method.
In the onPostExecute method after parsing is complete, dismiss the ProgressDialog that was set in the main activity.
I could do this by passing the ProgressDialog object to the parsing class and dismissing the same object in its onPostExecute method.
I think passing an instance of UI object as argument is not a good approach to program, I hope there must be some other ways to work around.
Please suggest.
Thank you
The easiest way to decouple these is to use an interface:
Define a call-back interface (let's call it WorkDoneListener) with a single method: workDone().
Declare your activity class to implement WorkDoneListener and implement workDone() to dismiss the dialog.
Define the AsyncTask's constructor to accept a WorkDoneListener. Stash the reference in a member field.
In onPostExecute, call the listener's workDone() method.
Ted's answer is what you should do if your AsyncTask is too big and you want to declare it in other file. However, keep in mind that usually you declare the AsyncTask inside your UI class:
public class YourActivity extends Activity{
private class YourAsyncTask extends AsynkTask<etc.>{
}
}
In fact, if you are using you AsyncTask from that activity only (I mean, if you are not using it anywhere else), declaring the AsyncTask as a inner class is a good design practice.

Getting Reference to Calling Activity from AsyncTask (NOT as an inner class)

Is it at all possible, from within an AsyncTask that is NOT an inner class of the calling Activity class, to get a reference to the instance of Activity that initiated execution of the AsyncTask?
I am aware of this thread, however it doesn't exactly address how to reference the calling Activity. Some suggest passing a reference to the Activity as a parameter to the AsyncTask constructor, however, it's reported that doing so will always result in a NullPointerException.
So, I'm at a loss. My AsyncTask provides robust functionality, and I don't want to have to duplicate it as an inner class in every Activity that wants to use it. There must be an elegant solution.
The "elegant solution" is to actually try passing it as a parameter (to the constructor or execute()) and see if it works, rather than assuming the person who asked that previous question (then answered his own question twice) knows what he is doing. I can think of nothing intrinsic to AsyncTask that would cause Activity to be a bad constructor parameter and every other object be just fine.
Now, I haven't passed an Activity (or other Context) as a parameter to an AsyncTask, because my AsyncTasks are always private inner classes. In fact, the fact that you want a public AsyncTask to me is a code smell, suggesting these tasks should be mediated by a Service or some other control point. But, that's just me.
UPDATE
A better answer for handling this pattern can be found here: Background task, progress dialog, orientation change - is there any 100% working solution?
My AsyncTasks always live in a separate package while still bound to a particular type of Activity. They accept it's instance in constructor and store in a local variable.
Try thinking in terms of creating an abstract Activity class that encapsulates AsyncTask-related stuff and is extended by other activities.
Like so:
public abstract RemoteListActivity<T> extends ListActivity{
// calls AsyncTask, shows spinning progress dialog, etc
protected abstract T someConcreteMethod();
}
public final class CustomerListActivity extends RemoteListActivity<Customer>{
protected final Customer someConcreteMethod();
}
Alternatively, if things don't fit in a single hierarchy, have an interface:
interface LazyLoadable {
void setLoadingState();
void setDefaultState();
}
public class MyActivity extends Activity implements LazyLoadable{
}
public final class AsyncTask extends AsyncTask<Void, Void, Void>{
private final LazyLoadable lazyLoadable;
public MyAsyncTask(Context ctx, LazyLoadable lazyLoadable){
super(ctx);
this.lazyLoadable = lazyLoadable;
}
}

Categories

Resources