I have objects (not on the ui thread) that need to run the async task as internal methods and I want to pass the ui thread to the method and then implement the ui thread on the asynctask that way - is there a way of doing this?
pseudo-code:
public class EditDetails extends Activity{
MyObject obj = new obj;
obj.syncWithServer(EditDetails.this);
}
public class MyObject {
public void syncWithWerver(EditDetails parent){
final class GetUserHttpTask extends AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
return "";
}
#Override
protected String onPostExecute(String result) {
//this doesn't run
}
}
}
}
note: at the moment this isn't working because onPostExecute isn't firing after the doInBackground
EDIT
this code is pseudocode the actual problem is still happening and I have listed it http://pastebin.com/jW6JpUbg here.. basically it gets stuck after running line 72 on the pastebin in never does onPostExecute
Weird enough the onPostExecute should be void. I wonder how is your code compiling as you have changed the return type of overridden method?
After you correct your onPostExecute you can get the AsyncTask run as follows:
final class GetUserHttpTask extends AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
return "";
}
#Override
protected String onPostExecute(String result) {
// this will run
}
}
public void syncWithWerver(EditDetails parent){
AsyncTask task = new GetUserHttpTask();
task.execute();
}
Did you tried executing your task like this ?
parent.runOnUiThread(new Runnable() {
#Override
public void run() {
new GetUserHttpTask().execute();
}
});
I think this should work..
Added:
Your AsyncTask implementation should be as below :
Note : Read the updated comments
class GetUserHttpTask extends AsyncTask<String/* in parameter for doInBackground */, Boolean /* in parameter for onProgressUpdate */, String /* Out parameter and in parameter for onPostExecute method*/> {
#Override
protected String doInBackground(String... params) {
return "";
}
#Override
protected void onPostExecute(String result) {
// this doesn't run
}
#Override
protected void onProgressUpdate(Boolean... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
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);
}
}
}
String[] a = new String[2];
String[] b = new String[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
new AsyncTaskClass().execute();
// in here when i use a it gets me a but i write a = b in method().
}
class AsyncTaskClass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
method();
return null;
}
#Override
protected void onPostExecute(String s) {
}
}
void method() {
a = b;
}
method() is working i put a toast messg in it and i saw the mssg,but it doesnt work(a=b)
by the way a and b is defined.we call that a={"a","b"}; b={"c","d"}; when i use a[0] code gets me "a". why? this is the question
doInBackground is being executed in background thread, so once you call .execute(), execution will pass your:
//in here when i use a it gets me a but i write a = b in method().
line, and your doInBackground will certainly not yet execute (but it might), you should move all your processing to onPostExecute if it depends on doInBackground results.
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);
}
My basic question is how do you update the GUI with AsyncTask. I am setting a String in onPostExecute that the GUI thread references. Using logging, I can see the String getting set in the onPostExecute method, but it never gets set on my GUI under my onClickListener to update the GUI. Any help is appreciated.
Main Program:
public class Main extends Activity {
/** Called when the activity is first created. */
Arduino.ToAndroid.Temperature.GetJSON jsonHttpClass = new Arduino.ToAndroid.Temperature.GetJSON();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetJSON().execute(url_to_Http);
}
View.OnClickListener temperatureListener = new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// buttonTemperature = json.getTemp();
tempView.setText(jsonHttpClass.value);
Log.i("ROSS LOG", "Button Clicked");
}
}; }
Async Task:
class GetJSON extends AsyncTask {
public String value;
#Override
protected String doInBackground(String... url) {
String result = this.getHttpJson(url[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
value = new String(result);
Log.i("ROSS LOG", value);
}
}
In onCreate(), you should be using the handle for the already created object of the AsyncTask and not create a new object.
Use
jsonHttpClass.execute(url_to_Http);
instead of
new GetJSON().execute(url_to_Http);
I don't understand why I'm getting this error. I'm using AsyncTask to run some processes in the background.
I have:
protected void onPreExecute()
{
connectionProgressDialog = new ProgressDialog(SetPreference.this);
connectionProgressDialog.setCancelable(true);
connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
connectionProgressDialog.setMessage("Connecting to site...");
connectionProgressDialog.show();
downloadSpinnerProgressDialog = new ProgressDialog(SetPreference.this);
downloadSpinnerProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downloadSpinnerProgressDialog.setMessage("Downloading wallpaper...");
}
When I get into doInBackground() depending on a condition I:
[...]
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
[...]
Whenever I try downloadSpinnerProgressDialog.show() I receive the error.
Any ideas guys?
The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.
You have to call show() either in onProgressUpdate() or in onPostExecute().
For example:
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
#Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
}
}
I had a similar issue but from reading this question I figured I could run on UI thread:
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
alertDialog.show();
}
});
Seems to do the trick for me.
I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
#Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
alertDialog.show();
}
});
}
}
final Handler handler = new Handler() {
#Override
public void handleMessage(final Message msgs) {
//write your code hear which give error
}
}
new Thread(new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(1);
//this will call handleMessage function and hendal all error
}
}).start();