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
Related
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 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.
I usually use AsyncTask in the same class with the caller, but now I want to call asyntask from different class using interface class,I want to get value from onProgressUpdate call from another clas, this my asynctask class..
class UploadFileToServer extends AsyncTask<String, Integer, String> implements DialogInterface.OnCancelListener {
private String url;
private File file;
ShareProgress shareProgres;
SharePosExecute sharePosExecute;
public UploadFileToServer(String url, String file) {
this.url = url;
this.file = new File(file);
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... v) {
//place code of upload file to server,run very well...
return responseFromServer;
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("progress",progress[0]+""); //this work well
shareProgres.progressUpdate(progress[0]); //I get error in here
}
#Override
protected void onPostExecute(String response) {
sharePosExecute.posExecute(response); // i also get error in here
}
#Override
public void onCancel(DialogInterface dialog) {
cancel(true);
// dialog.dismiss();
}
}
in my activity class
public class myActivity extends SherlockFragmentActivity implements ShareProgress,SharePosExecute {
#Override
public void progressUpdate(int progress) {
Log.i("progress in myactivity",progress+""); //i want to this code work.
}
#Override
public void posExecute(String output) {
Log.i("processFinish myActivity",output);
}
}
I use interface class for comunicated with diferent class, here my interface code
public interface ShareProgress {
void progressUpdate(int progress);
}
how do i fix this,may be there is another ways for this, please help
thanks
you should be setting your Listener in your asynctask right?
ShareProgress shareProgres;
SharePosExecute sharePosExecute;
public UploadFileToServer(String url, String file,ShareProgress shareProgres,SharePosExecute sharePosExecute) {
this.url = url;
this.file = new File(file);
this.shareProgres=shareProgres;
this.sharePosExecute=sharePosExecute;
}
and in your activity,start initialize your async task:
UploadFileToServer uFTS=new UploadFileToServer(url,file,myActivity.this,myActivity.this);
//then execute:
uFTS.execute();
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.
The project I'm working on is slightly more complicated but I made this simple test to try to track down what was wrong with my code. The progress dialog never dismisses. I had it at one point where they weren't returning null. '
public class SyncTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new mTask(this).execute();
}
public class mTask extends AsyncTask<Void, Void, Void> {
Context mContext;
ProgressDialog progressDialog;
public mTask(Context aContext) {
mContext = aContext;
}
#Override
public void onPreExecute() {
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("New...");
progressDialog.show();
}
#Override
public Void doInBackground(Void... params) {
return null;
}
public Void onPostExecute(Void... params) {
progressDialog.dismiss();
return null;
}
}
}
The parameters are wrong, use this:
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
return;
}
I am agree with Cesar and Shailendra answers, but still let me make little improvement over it:
#Override
protected void onPostExecute(Void result) {
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
return;
}
Missing #Override notation before onPostExecute. Also return null is not required.