How to run queries in the background - android

I have listed of products with different category. I have to sort them. Because of the queries, It is taking more time to load. Between two activities, the screen is coming black. I want to run the query in the background. How can I do that and how to use its result in main activity?
private class InsertTask extends AsyncTask {
String cat;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
Boolean success = false;
try {
category(cat);
success = true;
} catch (Exception e) {
if(e.getMessage()!=null)
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
}
private void category(String category) {
try{
Cursor1 = mDbHelper.fetchcategory(category);
}catch(Exception e){
Log.v("Excep", ""+e);
}
}
And when called
InsertTask task = new InsertTask();
task.execute();
I have listed the category in buttons. How can I get the values then?

You should use AsyncTask for that. And some more info.

Its good you have thought of AsyncTask. Firstly, you can declare this class as inner in you class activity (if you haven't previously did) and so you are able to access you view class members.
You can do this also by creating thread and one handler that will be used to update your UI components. Remember that if you use threads you'll need to lock/unlock your database object because of the thread safety(if any other thread is accessing the database for any reason). Read more about thread safety of dbs.

I was doing some searching myself, and I came across this read, its rather long but looks extremely helpful, with lots of code examples. (I bookmarked it for myself).
Threads, Async, and Handlers O MY!
But some form of threading is the ticket.
From Android dev.
(My favorite code snippet)
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
//Do Work here
}
}).start();
}

Related

Android AsynchTask in Linear Layout - Method must be called from UI Thread

I'm using AsynchTask in my app to save a record to a server.
The method that I use in my doInBackground doesn't do anything at all with the UI but I'm getting the following error
Method tryThis must be called from the UI thread, currently inferred thread is worker
Like I said nothing was happening that involved the UI. So I've stripped back my code to try to identify the problem and it is now pretty much bare.. see below
You will notice that rather than the AsynchTask code being in an extension of Activity it is in an extension of LinearLayout as I am using this is for a custom view. I strongly suspect that this is where the root of the problem lies but I don't understand why and nor do I know how to get around it.
public class ExerciseView extends LinearLayout {
public ExerciseView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private class saveRecordTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String returnString = "";
try {
returnString = tryThis();
//
} catch (Exception e) {
e.printStackTrace();
}
return returnString;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
//startProgress();
}
#Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
public String tryThis() {
String hi = "hi";
return hi;
}
}
I guess I could use an interface in the custom view to give the data to the Activity at the right time and then do the AsynchTask in the Activity but I'd really like to keep everything together in the custom view to minimise the amount of code that needs to written each time I use it.
Try this. It would help.
If you want to call tryThis() inside UI thread call it as following
runOnUiThread(new Runnable() {
#Override
public void run() {
tryThis();
}
});

Source not found on AsyncTask.execute()

I am trying to get along with AsyncTask..
what my problem was that i was building a table of textviews dynamically, based on the output of a procedure.. But then i figured that by using asynctask i can do it in a more efficient way..So, what i did is as follows:
private class DisplayReport extends AsyncTask<Void, Void, Boolean>{
protected void onPreExecute(){
//Message -- "Please wait while the Report Loads..."
}
#Override
protected Boolean doInBackground(Void... params) {
//Here i fetch the data from the procedure via a web service
//parse the result of web service and set a bool variable true or false based on whether the dataset fetched is empty or not.
}
protected void onPostExecute(Boolean value){
if(value == true){
"Please try again later!!"
}
else{
runOnUiThread(GenTable);
}
}
private Runnable GenTable = new Runnable(){
public void run(){
try {
displayReport(result); // in this method i build the table.
} catch (Exception e) {
ad.setTitle("Error..");
ad.setMessage(e.toString());
}
}
};
}
the above async class is an inner class in my main class which extends activity.
and this is how i am executing the asynctask..
DisplayReport dr = new DisplayReport();
dr.execute();
now when i debug, i get the "source not found" error on dr.execute()..
i tried searching a lot on the net, but i simply cannot find out anything concrete. Also, please let me know if my approach is incorrect..
this question might seem very silly, but i am new to android and java as well and any help would be really great..
Thanks!
Execute is going to start a new thread. You don't want to debug into it. Instead, put breakpoints in onPreExecute, doInBackground, and onPostExecute and you can see when each of those gets called.
onPostExecute is already being run in the UI thread, so you should not create another runnable for it. Just make your onPostExecute like this:
protected void onPostExecute(Boolean value){
if(value == true){
String message = "Please try again later!!";
// Do something here with your message
}
else{
displayReport(result);
}
}

How to work with AsyncTask and threads?

The goal:
Using Google App Engine server and Android client, I'm trying to put on the Google map at the Android client Users overlays. Every 30 seconds I'm polling the server and getting Vector that contains users and adding it to the map.
Current status:
I'm dong all that using in one new thread, So after running the app I got:
weird behaviors(delayed overlays, multiple overlays) and after that crushed with ConcurrentModificationException.
After reading a bit i figured out that I need to work with AsyncTask.
Correct me if I'm wrong,But I understand that everything done in the Activity at at onCreate is "running" in UIhread so I need to put the "Logic" (All the Network handling) in doInBackground and all the UI Handling like putting overlays on the map in onPostExecute.
My Question are:
1) In the current status I'm doing:
new Thread()
{
#Override
public void run()
{
super.run();
while(true)
{
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
putNewOnlineUserOnTheMap();
}
}
}.start();
What is the right way to convert this To AsyncTask?
Do I poll the server still using new thread in the doInBackground or there is right way to do this?
2) Is there a specific list of what counts as UI to put in onPostExecute or any concepts list?
In my case I guess that in need to put putNewOnlineUserOnTheMap() in onPostExecute.
Thanks.
Something similar to the following:
class UpdateTask extends AsyncTask<Void, Vector, Void>{
#Override
protected Void doInBackground(Void... params) {
// this is running in a background thread.
while (!isCancelled()) {
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
// send the result back to the UI thread
// onProgressUpdate will be called then
publishProgress(responseFromServer);
}
return null;
}
#Override
protected void onProgressUpdate(Vector... values) {
// this is executed on the UI thread where we can safely touch UI stuff
putNewOnlineUserOnTheMap(values[0]);
}
}
You can't use the result of the task since the task is finished then. But you can use the progress publishing mechanism to get periodic results. If you use it like that and do the modification on the UI thread you should not get ConcurrentModificationException because you do the modifications on the one thread that can safely modify the UI.
One thing to note here: create new instances of your Vector in the background thread and then use it to update the UI. But don't touch the same object afterwards in the backgroundthread. That way you don't need any synchronization since after the background thread sends it away it is only the UI thread that touches it. (and you could use a simple ArrayList instead of a Vector)
AsyncTask uses generics and varargs.The parameters that are passed to the asyntask are . TypeOfVariableArgumentsParameters is passed into the doInBackground(), ProgressParam is used for progress information and ResultParam must be returned from doInBackground() and is passed to onPostExecute() as parameter.
example:--
protected class ParsingTask extends AsyncTask> {
private ProgressDialog loadingDialog = new ProgressDialog(JsonParserActivity.this);
protected void onPreExecute() {
loadingDialog.setMessage("loading app store..");
loadingDialog.show();
}
#Override
protected ArrayList<Items> doInBackground( Context... params ) {
// do ur process here.
return result;
}
if (!this.isCancelled()) {
}
return result;
}
#Override
protected void onProgressUpdate(String... s) {
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( ArrayList<Items> response ) {
//if u r dealing with list view and adapters set the adapter here at the onPostExecute()
loadingDialog.dismiss();
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled", 1).show();
}
}
You can use AsyncTask like below. Hope this will help you..
Class YourClass{
void YourClass(){
NetworkTask nT = new NetworkTasK();
nT.execute();
}
}
protected class NetworkTask extends AsyncTask<Void, String, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
try
{
String response;
while(keepreceiving)
{
response = in.readLine();//Prog Counter stops here until getting i/p.
if(response != null)
yourFunctionForResponse(response);
}
}
catch (Exception ex)
{
}
return null;
}
private void yourFunctionForResponse(String response){
//things to do....
}
}
You may also try runOnUiThread(Runnable action) along with this to implement your work.

how to do dynamic loading in android?

i have an rss feed that comes via an XML. There are several events that are returned with information about them. The events are returned with tags...for eg: ....info...
as soon as i encounter tag, i want to update the listview that i am using to show the events.
So the user does not see the loading progress dialog, rather he sees the events getting added to a list.
How do i do this.
thank you in advance.
Here's pseudo codeish example for one way of doing this using SAX parser;
// MyParserThread is assumed to be inner class of Activity here.
private class MyParserThread extends Thread implements MyParserObserver {
private MyParser mParser;
public MyParserThread() {
mParser = new MyParser();
mParser.setObserver(this);
}
public void run() {
try {
// load xml
mParser.parse(xml);
} catch (Exception ex) {
}
}
public void onMyParserEvent(final DataReceivedFromParsing data) {
runOnUiThread(new Runnable() {
public void run() {
// update data to your UI.
}
});
}
public void cancel() {
mParser.cancel();
}
}
And in your parser you're implementing ContentHandler
public void cancel() {
mCancelled = true;
}
public void startElement(....) {
if (mCancelled) {
// If you want to stop Thread from running, all you have to do
// is make parsing stop.
throw new SAXException("Cancelled");
}
....
}
And triggering parsing once your onCreate is called would be;
public void onCreate(...) {
...
mParserThread = new MyParserThread();
mParserThread.start();
...
}
Now this isn't perfect but hopefully gives some idea how to do Thread handling for this purpose. Fundamentally you just have start it, and adding 'cancel' functionality is somewhat more of a bonus - e.g. for cases in which Activity is destroyed while your Thread is running.

How do I cancel an AsyncTask

I am using an Asynctask as the loop controller for a game and noticed that the thread created kept on running after the activity was finished.
I realised that was the correct behaviour of a separate thread and then I tried hunting down answers on how to end the thread when the app enters onPause.
I found lots of similar questions but no direct answers but eventually came up with a method so I'm going to answer my own question here to hopefully help others in future. (And to receive improvements to my answer as well)
Firstly, AsyncTask have a fully valid cancel() method. Secondly, do not use an AsyncTask for a proper game loop. AsyncTask isn't for long-running operations.
Therefore, skip AsyncTask for your game loop and learn how to properly manage pausing / resuming in an ordinary Thread by reading another answer from me here on SO.
public class CamOverlayTest extends Activity {
//...
public static BackgroundLoop BackgroundLoopTask;
//...
#Override
protected void onResume() {
//...
BackgroundLoopTask = new BackgroundLoop();
BackgroundLoopTask.execute();
}
#Override
protected void onPause() {
//...
BackgroundLoopTask.cancel(true);
}
private class BackgroundLoop extends AsyncTask<Void,Integer,Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
int count =0;
while (!this.isCancelled()) {
// Basically, this is where the loop checks if the Aysnctask has been asked to be
// cancelled - if so - it exits.
try {
Thread.sleep(1000);
updatePhysics(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
count +=1;
Log.i("SW","Count: "+count);
publishProgress();
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// swDrawOnTop is my view
swDrawOnTop.invalidate();
}
//...
}

Categories

Resources