Android SDK - running functions in the background - java

I have a function which can vary in the time it takes to finish. I would like to display a progress dialog whilst this function is operating.
I am aware that you can use a 'Thread' to achieve this. Can someone point me in the right direction for doing this ?
EDIT:
Here is the code I am using:
private class LongOperation extends AsyncTask<String, Void, String>
{
ProgressDialog dialog;
public Context context;
#Override
protected String doInBackground(String... params) {
if (!dialog.isShowing())
dialog.show(); // Just in case
return null;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute()
{
dialog = ProgressDialog.show(context, "Working", "Getting amenity information", true);
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
#Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
}
this is the Asnyc class. The user selects an option from the menu, and this is then executed:
longOperation.execute(""); // Start Async Task
GetAmenities(Trails.UserLocation); // Long function operation

You should use AsyncTask for this purpose. See Android developers website and How to use AsyncTask.
Some sample code:
private class LongRunningTask extends AsyncTask<Void, Boolean, Boolean> {
private ProgressDialog progress;
protected void onPreExecute() {
progress = ProgressDialog.show(yourContext, "Title", "Text");
}
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
protected void onPostExecute(Boolean result) {
if(result) {
progress.dismiss();
}
}
}

Take a look at this page:
Progress Bar Reference
Greetings

public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork();
}
}).start();
}
taken from here
http://developer.android.com/resources/articles/painless-threading.html

Related

How to show ProgressDialog when AsyncTask start gathering data from the server till when it gets all the data

I would like to make an app which displays some data from the server. When I log in as an admin, I would like there to be a progress dialog until the application gets all the data from the server.
I have 3 Classes. Main Activity(login screen), SecondActivity(displays data) and BackgroundWorker(which extends AsyncTask).
I know that in on postExecute I have to close ProgressBar
Override
protected void onPreExecute() {
if(activity.getClass() == MainActivity.class) {
this.progressDialog.setMessage("Please wait for a while.");
this.progressDialog.setTitle("Login");
this.progressDialog.show();
}
else
super.onPreExecute();
}
#Override
protected void onPostExecute(final String result) {
if(activity.getClass() == MainActivity.class) {
new CountDownTimer(1000, 500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
System.out.println(result);
if (result.equals("Username or password is not correct")) {
alertDialog.setMessage(result);
alertDialog.show();
} else if(result.equals("is Admin")) {
Intent intent = new Intent(activity,Admin.class);
intent.putExtra("username",user);
activity.startActivity(intent);
activity.finish();
}
progressDialog.dismiss();
}
}.start();
}
I have made like this for login Screen but I don't think it is wise to delay the application on purpose. And also my implementation doesn't work if I call AsyncTask class twice in one activity. Any suggestion?
You can use this code:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Do your request
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pd != null)
{
pd.dismiss();
}
}
}
Take a look at this link, if you want!
Good luck with your android development!

ProgressDialog new Activity Asynctask is not showing, why?

I made a AsyncTask class with the following code
public class removeDialog extends AsyncTask<Void, Void, Void> {
Context c;
ProgressDialog asyncDialog;
String page;
public removeDialog(Context c, String page) {
this.c = c;
this.page = page;
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
if (page == "algemeneVoorwaarden") {
Intent intent = new Intent(c, algemeneVoorwaarden.class);
c.startActivity(intent);
}
if (page == "contact") {
Intent intent = new Intent(c, contactTest.class);
c.startActivity(intent);
}
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
First time I tried:
on the first time I see an ProgressDialog, but the second time I want to open the activity I get nothing.
Second time I tried:
I get no ProgressDialog even the first time I try.
I execute my code in an AsyncTask class, code:
voorwaarden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new removeDialog(c, "algemeneVoorwaarden").execute();
}
});
Does someone know why it isn't working? Please help me.
Your dialog will be dismissed as soon as it's shown, because your doInBackground is empty. Try adding a Thread.sleep() with a few seconds, just to simulate a delay.
Also, I suspect that the new activities you're starting will leave your dialog behind. So I would suggest you to test the code without these new activities for now.
public class RemoveDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog asyncDialog;
public RemoveDialog(Context c) {
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}

Android AsyncTask runs multiple times

In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes.
How can i avoid this error with using asynctask?
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
thanks...
You can create a boolean flag (let's say bDiscardButtonAction), and set it to true in onPreExecute() and set it to false in onPostExecute(), something like:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
#Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
#Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
#Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
#Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}
disable the show button in onPreExecute() and enable it back onPostExecute().
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
#Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
#Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
#Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}
I hope this code will help u out.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
#Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}

protected void onPostExecute error

When I try to implement the onPostExecute method it gives me an error to remove #Override and that a super class or method needs to be called. However, I did call the superclass and such. Here is my code of my Asynctask.
public class parsenfill extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
JsonParsing parse = new JsonParsing(url);
parse.parseFile(3, urls);
return null;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void...voids ) {
super.onPostExecute(voids);
//Body of method
}
}
Remove the ... from the method signature. The parameter type of onPostExecute is the return type of doInBackground() i.e. just plain Void in your case.
Try this
private class MyAsyncClass extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
/**
* invoked on the UI thread before the task is executed. This step
* is normally used to setup the task, for instance by showing a
* progress bar in the user interface.
*/
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
/**
* Invoked on the background thread immediately after onPreExecute()
* finishes executing. This step is used to perform background
* computation that can take a long time. The parameters of the
* asynchronous task are passed to this step.
*/
return null;
}
#Override
protected void onPostExecute(Void result) {
/**
* Invoked on the UI thread after the background computation
* finishes. The result of the background computation is passed to
* this step as a parameter.
*/
super.onPostExecute(result);
}
}
Then you have to call this async class on UI thread like this.
new MyAsyncClass().execute();
Wrong:
#Override
protected void onPostExecute(Void...voids ) {
super.onPostExecute(voids);
//Body of method
}
because ... stands for string array and your background returns void.
Correct:
#Override
protected void onPostExecute(Void voids ) {
super.onPostExecute(voids);
//Body of method
}

Why should I use onPrepareDialog etc. to show a ProgressDialog in Android?

I'm currently using the following code to show / hide a ProgressDialog in my Andorid app (called from withing MyActivity):
private void startTask() {
new MyTask().execute();
}
private class MyTask extends AsyncTask<A, String, C> {
private ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
this.pd = ProgressDialog.show(MyActivity.this, "Title", "Message", true, true);
pd.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
MyTask.this.cancel(true);
}
});
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
this.pd.setMessage(values[0]);
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(MyActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(RequestResult result) {
super.onPostExecute(result);
this.pd.dismiss();
}
}
Now, since I read so much about onCreateDialog in Activities, I just want to know if my way of doing it has any downsides I didn't think of, or even why I should prefer the onCreateDialog mechanism.
[UPDATED]
The problem with this approach is that in case Activity will be destroyed (e.g. on rotation) your AsyncTask will retain it in memory, thus create a temporary memory leak. Also, it will cause an IllegalArgumentException while attempting to access ProgressDialog after activity's onDestroy().

Categories