My asynctask not going in onProgressUpdate. why? I'm going to create progress bar in asynctask. Below is my code to show uploading image by using progress bar.
public static class RegisterDataEngineForPost extends AsyncTask<MultipartEntity, integer, String>{
ProgressBar ProgressBarUpload;
public void setmCurrentPhotoPath(ProgressBarUploadb) {
ProgressBarUpload = ProgressBarUploadb;
}
#Override
protected void onProgressUpdate(integer... values) {
}
#Override
protected void onPreExecute() {
ProgressBarUpload.setProgress(0);
}
#Override
protected String doInBackground(MultipartEntity... params) {
}
#Override
protected void onPostExecute(String result) {
}
}
}
Use http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)
manually, Android will not know your progress out of nothing, you need to determine it yourself.
You have to call publishProgress(progress_value) to update the progress like that
public static class RegisterDataEngineForPost extends AsyncTask<MultipartEntity, integer, String>{
ProgressBar ProgressBarUpload;
public void setmCurrentPhotoPath(ProgressBarUploadb) {
ProgressBarUpload = ProgressBarUploadb;
}
#Override
protected void onProgressUpdate(integer... values) {
}
#Override
protected void onPreExecute() {
ProgressBarUpload.setProgress(0);
}
#Override
protected String doInBackground(MultipartEntity... params) {
//do some task and update the progress
publishProgress(progress_value);
}
#Override
protected void onPostExecute(String result) {
}
}
}
Related
Here is my problem. I have created a asyncTask to link to my database and send and receive information using JSON.
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
returnValues = dataParsed.split("\\s+");
mainActivity.getValue(this is the function that calls anotherfunction in
asyncTask)
Log.v("ARRAY LENGTH", String.valueOf(returnValues.length));
}
public String[] returnmyString(){
//return mySaveData;
Log.v("ARRAY LENGTH 2", String.valueOf(returnValues.length));
return returnValues;
}
I create the asyncTask object within my activity based class and then call that object.execute. My problem is that my code will continue to run once calling the object.execute and one of the lines calls a function within the asyncTask class before it is done executing all the code.
process.activitySave(1); //<---Process is the object for the asyncTask class
process.ContextSave(this,ServerURLSource,myParameters);
process.execute()
changedData = process.returnmyString(); //<-- this is the line of code that gets implemented that returns a null value
I have tried creating a Mainactivity object in the asyncTask class and then calling a function then that retrieves the value but my app crashes when I do this. any help would be appreciated. I would like to put some sort of listener in the mainactivity class as it seems I cannot reference any of the functions from my mainactivity class in my asyncTask class.
This is the function within the asyncTask to return the value:
public String[] returnmyString(){
//return mySaveData;
Log.v("ARRAY LENGTH", String.valueOf(returnValues.length));
return returnValues;
}
Method 1 is the basic, anonymous inner class implementation. Because of the inner AsyncTask class is not static class, you can access to the CustomActivity's properties from that implementation.
In Method 2, AsyncClass implemented separately. If you gave your activity to this class, it can be call back your desired method after execution. This method, for our example is the #setChangedData method. CustomAsyncTask call backs the #setChangedData in the #onPostExecute.
public class CustomActivity extends AppCompatActivity {
String mChangedData;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Method 1 - change data into the anonymously implemented AsyncTask class
new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CustomActivity.this.mChangedData = "foo"; // this changes mChangedData as "foo"
}
}.execute(1);
// Method 2 - change data into the custom AsyncTask class
new CustomAsyncTask(this).execute(2);
}
public void setChangedData(String changedData){
this.mChangedData = changedData;
}
static class CustomAsyncTask extends AsyncTask<Integer, Void, Void> {
CustomActivity mActivity;
public CustomAsyncTask(CustomActivity activity) {
this.mActivity = activity;
}
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.setChangedData("bar");
}
}
}
And, as method 3, if you want to separate you Activity and AsyncTask more loosely, this is the handler method:
public class CustomActivity extends AppCompatActivity {
private String mChangedData;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomAsyncTask task = new CustomAsyncTask();
task.setOnDataChangedListener(new CustomAsyncTask.OnDataChangedListener() {
#Override
public void onDataChanged(String data) {
mChangedData = data;
}
});
task.execute(1);
}
private static class CustomAsyncTask extends AsyncTask<Integer, Void, Void> {
private OnDataChangedListener onDataChangedListener;
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(onDataChangedListener != null) {
onDataChangedListener.onDataChanged("foo");
}
}
void setOnDataChangedListener(OnDataChangedListener onDataChangedListener) {
this.onDataChangedListener = onDataChangedListener;
}
interface OnDataChangedListener {
void onDataChanged(String data);
}
}
}
class activity and splash.class. In the first (which execute the main program), has asynctask (it will be call several time) retrieving data. The second activity is a splash screen which run until the data are downloaded.
public class splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
startHeavyProcessing();
}
private void startHeavyProcessing(){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, String, String> {
Intent i = new Intent(splash.this, MainActivity.class);
#Override
protected String doInBackground(String... params) {
startActivity(i);
return "";
}
protected void onPostExecute(String result) {
}
protected void onPreExecute() {
}
protected void onProgressUpdate() {}
}
}
I would like to finish spalash activity, when MainActivity finished to retrieve data in its doInBackground. Once done, I would run MainActivity only.
Try this!
private class LongOperation extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
return "";
}
protected void onPostExecute(String result) {
if(result != null){
}
Intent i = new Intent(splash.this, MainActivity.class);
startActivity(i);
}else {
Log.e("DOWNLOAD ERRO");
}
protected void onPreExecute() {
}
protected void onProgressUpdate() {}
}
I have several different AsyncTasks that need to perform the same shared basic operation and show progress while doing so. Rather than copying a lot of code several times (with progress showing in each) is there a way to share the code by passing in the other class? The AsyncTasks are very different and you can't just pass in the Abstract, which has a protected publishProgress() method anyway. Looked at a bunch of examples and tried to a lot of different variations without success.
So here are the details...lets say we have two different tasks doing different stuff, but sharing the need to hit a server, download a number of files and then put them in a DB (and then do other stuff):
public class ExampleTaskFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
mProgress.dismiss();
}
private void showProgress(String message) {
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
mProgress.setMessage(message);
}
public class TaskA extends AsyncTask<Object, String, ArrayList<A>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<A> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffA();
}
#Override
protected void onPostExecute(ArrayList<A> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<A> doMoreStuffA() {
return new ArrayList<A>();
}
}
public class TaskB extends AsyncTask<Object, String, ArrayList<B>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<B> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffB();
}
#Override
protected void onPostExecute(ArrayList<B> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<B> doMoreStuffB() {
return new ArrayList<B>();
}
}
}
public class DoStuffPublish {
private AsyncTask task;
public DoStuffPublish(AsyncTask task) {
super();
this.task = task;
doSharedStuff();
}
protected void publishProgress(String message) {
if (task instanceof TaskA) {
((TaskA)task).progressUpdate(message);
}
else if (task instanceof TaskB) {
((TaskB)task).progressUpdate(message);
}
}
public void doSharedStuff() {
publishProgress("Doing Shared stuff...");
// Do lots of shared things here...
publishProgress("Done doing shared stuff...");
}
}
This code has been cobbled together - so don't get too hung up on the syntax. The concept it there...I want to have a shared class I can call in 2 or more tasks that can share that code and still publish updates. I have tried putting the ProgressDialog in the tasks and outside without success. When I have done so I get "Only the original thread that created a view hierarchy can touch it's views". And in the debugger you can see the two different threads - the original main UI thread and the thread created in the Form doInBackground(Object... params).
I fear this may not be possible...
robinj - had it correct, just needed to read his/her answer a little better. The trick was to code it like this:`public class ExampleTaskFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
mProgress.dismiss();
}
private void showProgress(String message) {
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
mProgress.setMessage(message);
}
public class TaskA extends AsyncTask<Object, String, ArrayList<A>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<A> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffA();
}
#Override
protected void onPostExecute(ArrayList<A> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<A> doMoreStuffA() {
return new ArrayList<A>();
}
}
public class TaskB extends AsyncTask<Object, String, ArrayList<B>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<B> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffB();
}
#Override
protected void onPostExecute(ArrayList<B> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<B> doMoreStuffB() {
return new ArrayList<B>();
}
}
}
public class DoStuffPublish {
private AsyncTask task;
public DoStuffPublish(AsyncTask task) {
super();
this.task = task;
doSharedStuff();
}
protected void publishProgress(String message) {
if (task instanceof TaskA) {
((TaskA)task).progressUpdate(message);
}
else if (task instanceof TaskB) {
((TaskB)task).progressUpdate(message);
}
}
public void doSharedStuff() {
publishProgress("Doing Shared stuff...");
// Do lots of shared things here...
publishProgress("Done doing shared stuff...");
}
}
`
Note the
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
Previously I had been trying to directly set the mProgress value, but it was in the wrong thread? Anyway thanks to robinj for the help! If you put an answer in I will thumbs it up...
In my android app, i am doing time consuming task extending AsyncTask, and want to display the progress in Toast messages. Toast messages are also displayed onPre() and onPost().
I am able to display Toast messages onPre() & onPost() but not able to show onProgressUpdate(Integer... progress).
Following is my code...
public class MainClass extends Activity {
public void Start(View view) {
DemoTasks runner = new DemoTasks(this);
runner.execute("Start");
}
private class DemoTasks extends AsyncTask<String, Integer, Integer> {
private Context context;
public DemoTasks(Context context){
this.context = context;
}
#Override
protected Integer doInBackground(String... params) {
try {
publishProgress(0);
doWork();
Thread.sleep(5000L);
publishProgress(100);
} catch (Exception localException) {
Log.d("POST", localException.getMessage());
}
return 100;
}
#Override
protected void onPostExecute(Integer result) {
Toast.makeText(context, "post", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(context, "progress-" + progress, Toast.LENGTH_SHORT).show();
}
}
}
Also in my doInBackgroud(String...params) ...Thread.sleep is also not working.
As soon as onPre() gets executed, onPost() also executes after that!!!!
You can try this,
showProgress ();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dialog.cancel();
Intent i=new Intent(getApplicationContext(),Main.class);
startActivity(i);
finish();
}
}, 3000); //number of seconds
private ProgressDialog dialog;
public void showProgress () {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Please wait");
dialog.show();}
Bascially,you can access the UI on any method, even In doinBackground you can access the UI using runOnUIthread.
here is one AsyncTask Example. This will show a peogress dialog while executing the task.
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
progressDialog.setMax(100);
progressDialog.setMessage("Please Wait..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.show();
}
protected void onPreExecute (){
}
#Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
// int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
progressDialog.setProgress(progress);
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
You can call this Task as,
new LoginProcessing(loginCredentials).execute();
In this Example loginCredentials is the parameter I am passing to the AsyncTask. You can change it to your own parameter.
I have AsyncTask class and I call it in my main class. I need to override the onPostExecute function and call inside ftpDisconnect(). But it does not work properly.
TempClass dj = new TempClass(serialnum) {
#Override
protected void onProgressUpdate(Integer... values) {
pr_bar.setProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
//dj.ftpDisconnect(); //need to make this happen
super.onPostExecute(result);
}
};
dj.execute();
My TempClass:
public class TempClass extends AsyncTask<String, Integer, String> {
public TempClass(String serialnum) {
this.serialnum = serialnum;
}
#Override
protected String doInBackground(String... params) {
//do stuff
return null;
}
public boolean ftpDisconnect() {
try {
mFTPClient.disconnect();
return true;
} catch (Exception e) {
}
return false;
}
}
You can't access that instance of dj without making it final. You should be able to call ftpDisconnect from inside the class:
#Override
protected void onPostExecute(String result) {
ftpDisconnect();
super.onPostExecute(result);
}