I have an IME service class and a long operation method in it. I want to run the LongOperation task in a asyncTask class that is in the IME Service class.
public class Myimeservice extends InputMethodService
implements KeyboardView.OnKeyboardActionListene {
//...
//some code here....
//...
public void setDictionary(){
//....
}
private class LongOperation extends AsyncTask<String, Void, String> {
private Myimeservice parent;
public LongOperation(Myimeservice pim){
parent = pim;
}
#Override
protected String doInBackground(String... params) {
Myimeservice tmp = new Myimeservice();
tmp.setDictionary();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
//app.hideLoading();
}
#Override
protected void onPreExecute() {
//app.showLoading();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
When i run it, the application forced to close. please help me.
I think the error is somewhere in your public void setDictionary() method.
I assume that you are manipulating a variable that is bound to the UIThread/MainThread, the application will crash since doInBackground is on another Thread.
Instead make the setDictionary() method return the dictionary and return it instead of "Executed" in doInBackground().
This will call the onPostExecute(Object result) which is run on UIThread/MainThread.
Something like this:
private class LongOperation extends AsyncTask<String, Void, Dictionary> {
#Override
protected Dictionary doInBackground(String... params) {
Myimeservice tmp = new Myimeservice();
Dictionary dict = tmp.setDictionary();
return dict;
}
#Override
protected void onPostExecute(Dictionary result) {
//do what ever you meant to do with it;
}
}
If you are not expecting any result from it you can just do:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
tmp.setDictionary();
}
});
I use the Runnable instead of AsyncTask and the problem solved.
final Runnable r = new Runnable(){
public void run(){
setDictionary();
}
};
this code is in onCreate() method of service.
Tanks a lot Tristan Richard.
Related
I want to run two connections using Android Native :
public class MyPublicClass extends AppCompatActivity {
here is the first class
private class GetNextQuestionIndex extends AsyncTask<String, Void, Void> {
//some code
protected Void doInBackground(String... params) {
URL url = new URL("url1");
//some code to initialize connection and get the output
MyPublicClass.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytxtview.setText(output1)
System.out.println("1");
progress.dismiss();
}
});
Here is the second class
private class GetLibelleOfQuestion extends AsyncTask<String, Void, Void> {
//some code
protected Void doInBackground(String... params) {
URL url = new URL("url2");
//some code to initialize another connection and get another output
MyPublicClass.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytxtview.setText(output2)
System.out.println("2");
progress.dismiss();
}
});
}//the end of the public class
but when i run my code its give me
2 1
how can I get
1 2
?
which means execute the run of GetNextQuestionIndex before the run of GetLibelleOfQuestion
onCreateActivity(...){
...
ShowDialog();
AsyncTask1(...).execute();
}
public void callAsyncTask2(){
AsyncTask2(...).execute();
}
class AsyncTask1(...){
....
onPostExecute(...){
activity.callAsyncTask2();
}
}
class AsyncTask2(...){
....
onPostExecute(...){
activity.dismissDialog();
}
}
Hope it helps.
This is the proper ways to call 2 asyn task .
private class GetNextQuestionIndex extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
URL url = new URL("url2");
//run your background task
return results;
}
#Override
protected void onPostExecute(String result) {
mytxtview.setText(output1)
System.out.println("1");
new GetLibelleOfQuestion ().execute("");
}
#Override
protected void onPreExecute() {
progress.dismiss();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
//Second asyn task
private class GetLibelleOfQuestion extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
URL url = new URL("url2");
//run your background task
return results;
}
#Override
protected void onPostExecute(String result) {
mytxtview.setText(output2)
System.out.println("2");
progress.dismiss();
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
oncreate method call or button click , where you want
new GetNextQuestionIndex ().execute("");
You can use set the second thread to sleep for a moment (waiting for the first thread to be executed):
private class GetLibelleOfQuestion extends AsyncTask<String, Void, Void> {
...
MyPublicClass.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Thread.sleep(WAIT_TIME_IN_MILLISECONDS);
mytxtview.setText(output2)
System.out.println("2");
progress.dismiss();
}
});
}//the end of the public class
I have a progress dialog, I want it to show and dismiss when my method has finished executing. now, I have this:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading...");
progressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try{
DownloadMethod(s);
progressDialog.dismiss();
}catch (Exception e){
Toast.makeText(prefs.this, "We can't reach the data...Try again", Toast.LENGTH_SHORT).show();
}
}
}).start();
My method DownloadMethod is executed but never shows the dialog.
Actually, It must be throwing an exception with progressDialog.dismiss(); call because you cannot update UI from a worker thread, instead use AsyncTask
e.g pass parameter to constructor
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
TypeOf_S s;
public DownloadFilesTask(TypeOf_S s){
this.s = s;
}
#Override
protected Void doInBackground(Void... obj) {
DownloadMethod(s);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
and call it like new DownloadFilesTask(s).execute();
or with generic parameter
private class DownloadFilesTask extends AsyncTask<TypeOf_S, Void, Void> {
#Override
protected Void doInBackground(TypeOf_S... obj) {
DownloadMethod(obj[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
and call it like new DownloadFilesTask().execute(s);
progressDialog.dismiss();is throwing an exception so move your code inside runOnUiThread() method like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
as suggested by Pavneet you can use async task as follows where AsyncTask<String, void, String> corresponds to the input type progress value and last is result value you are interested so give data types accordingly.
private class DownloadFilesTask extends AsyncTask<String, void, String> {
protected String doInBackground(String... urls) {
//here do the actual downloading instead of calling the DownloadMethod(s)
}
protected void onPreExecute() {
//here show the dialog
progressDialog.show();
}
protected void onPostExecute(String result) {
//here hide the dialog
progressDialog.dismiss();
}
}
and where you are calling the download function you just call this
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading...");
new DownloadFilesTask().execute(s);
//here s is assumed to be string type you can give anything
I would need some help to figure out how to return a doInBackground() value in AsyncTask which code is an interface. Here is an example
private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
public MyAsyncTask() {
super();
// do stuff
}
#Override
protected Boolean doInBackground(Void... void) {
checkIfContentAvailable(new interfaceMediaAvailableToDownload() {
#Override
public void onComplete(boolean resutl) {
return result; //This must be doInBackground return value, not onSuccess which is Void
}
#Override
public void onInternetError() {
return false; //This must be doInBackground return value, not onSuccess which is Void
}
};
}
#Override
protected void onPostExecute(Boolean result) {
if (result){
//Do stuff
}else{
//Do stuff
}
}
}
Obviously, this above code can't work because I don't know how to return onSuccess() value to doInBackground().
I hope this is clear enough....
EDIT
Okay my bad, I thought it would have been more readable to hide MyInterface usage, but I realize through your answers it is not. So I completed the code to add more details.
Any idea please?
Thank you in advance.
Create the object of the Mynterface in the place where you execute the AsyncTask.
Create a object reference of the MyInterface inside the AsyncTask ans set your interface object.
Then call the onSuccess method like below
`
private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
MyInteface myInterface;
setMyInterface(MyInterface interface){this.myInterface = interface;}
public MyAsyncTask() {
super();
// do stuff
}
#Override
protected Boolean doInBackground(Void... void) {
this.myInterface.onSuccess(); // or call on failure if failure happened
}
#Override
protected void onPostExecute(Boolean result) {
//Do stuff with result
}
}
`
Use it like ...
MyAsyncTask async = new MyAsyncTask();
async.setMyInterface(this);
async.execute();
Implement the interface in the place where your are executing.
This how you can do it.
In an existing app I have an activity with an inner class which extends AsyncTask, this looks like the following:
public class Activity_1 extends BaseActivity {
....
new async().execute();
...
public class asyncextends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... progress) { ... }
protected void onPreExecute() { ... }
protected void onPostExecute(String result) { ... }
}
}
Now, I need to call the same doInBackground-method from another activity, but the onPostExecute() of the this inner class operates on some local UI variables and hence it's not possible to use it from outside the clas.
Is there any way I can call this AsyncTask, and just override the onPostExecute andonPreExecute-method, or shall I create yet another inner-class in the other activity, do the same background thing (of course move it to common utility-class or something), etc...?
You can make a separate abstract package private class, extending AsyncTask and implementing doInBackground() method:
abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {
#Override
final protected String doInBackground(Void... progress) {
// do stuff, common to both activities in here
}
}
And in your activities just inherit from MyAsyncTask (new class probably should be private, by the way), implementing onPostExecute() and onPreExecute() methods:
public class Activity_1 extends BaseActivity {
...
new Async1().execute();
...
private class Async1 extends MyAsyncTask {
#Override
protected void onPreExecute(){
// Activity 1 GUI stuff
}
#Override
protected void onPostExecute(String result) {
// Activity 1 GUI stuff
}
}
}
If onPreExecute and onPostExecute contain some common actions as well, you can apply the following pattern:
abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {
public interface MyAsyncTaskListener {
void onPreExecuteConcluded();
void onPostExecuteConcluded(String result);
}
private MyAsyncTaskListener mListener;
final public void setListener(MyAsyncTaskListener listener) {
mListener = listener;
}
#Override
final protected String doInBackground(Void... progress) {
// do stuff, common to both activities in here
}
#Override
final protected void onPreExecute() {
// common stuff
...
if (mListener != null)
mListener.onPreExecuteConcluded();
}
#Override
final protected void onPostExecute(String result) {
// common stuff
...
if (mListener != null)
mListener.onPostExecuteConcluded(result);
}
}
and use it in your activity as following:
public class Activity_1 extends BaseActivity {
...
MyAsyncTask aTask = new MyAsyncTask();
aTask.setListener(new MyAsyncTask.MyAsyncTaskListener() {
#Override
void onPreExecuteConcluded() {
// gui stuff
}
#Override
void onPostExecuteConcluded(String result) {
// gui stuff
}
});
aTask.execute();
...
}
You can also have your Activity implement MyAsyncTaskListener as well:
public class Activity_1 extends BaseActivity implements MyAsyncTask.MyAsyncTaskListener {
#Override
void onPreExecuteConcluded() {
// gui stuff
}
#Override
void onPostExecuteConcluded(String result) {
// gui stuff
}
...
MyAsyncTask aTask = new MyAsyncTask();
aTask.setListener(this);
aTask.execute();
...
}
I wrote the code from the head, so it might contain errors, but it should illustrate the idea.
Its so simple just Simply build an object of main class and than call the inner class like this
OuterMainClass outer = new OuterMainClass();
outer.new InnerAsyncClass(param)
.execute();
this answer is too late to help you but hope it help others.
Thanks
1.Create a constructor of AsynckTask in ClassOne.
2.Crate object or ClassOne by new keyword.
3.Call Async Task by object
ClassOne{
class AsyncParmas extends AsyncTask {
public ADDloadGeofenceDetails() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
}
}
Class ClassTwo{
ClassOne obj= new ClassOne ();
obj.new AsyncParmas ().execute();
}
}
GoodLuck Who were facing problem.
If we create one static method which is in one class and and will be execute in any class in doInBackground of AsyncTask we can easily update UI through same class and even in different class .
I have a program that used async task everytime the button is clicked... I dont want to keep typing the WHOLE AsyncTask everytime it is clicked.. That will be to tedious. What is a better way i can do this?
Here is some source code.
new AsyncTask<Void, Integer, Void>(){
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
text1.setText("Nice to meet you "+name);
dismissDialog(typeBar);
}
#Override
protected void onPreExecute() {
typeBar = 0;
showDialog(typeBar);
}
}.execute((Void)null);
}
});
}
Create a new class that extends AsyncTask:
public class MyTask extends AsyncTask<Void, Integer, Void>
{
#Override
protected Void doInBackground(Void... arg0)
{
}
}
Then whereever you need it just do this:
new MyTask.execute();
Thats it! Have fun!
Put it in a public or private class. You can then reference/instantiate it based on the name of the newly made class.