My progressDialog doesn't roll? - java

I want to show a circle progressdialog when some functions run in backstage. so I write such a series of code:
pd = ProgressDialog.show(GridLayoutActivity.this, "","...");
new Thread(new Runnable() {
public void run() {
someFunc();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
But the progressDialog doesn't roll? why?

Try with Asynchronous task, here i post the example code, you may change as per you own
public class BackGround_Task extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
YourClassName.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//Your Background Task
return null;
}
protected void onPostExecute(Void result) {
//What will you do after the completion of Background process
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}

Just use something like this:
ProgressDialog progressDialog = new ProgressDialog(GridLayoutActivity.this);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.setMessage("...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
new Thread(new Runnable() {
public void run() {
someFunc();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();

Send handler message after try block. Use like this:
pd = ProgressDialog.show(SetFrames.this,"Loading", "Please Wait...",true);
new Thread() {
public void run() {
try {
//your function
}catch(Exception e)
{
}
handler.sendEmptyMessage(0);
pd.dismiss();
}
}.start();
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
}
};

Related

Android dialog dismiss after certain computation

I'm encountering the following problem:
I created a waiting spinner using Dialog like this
final Dialog progDialog = new Dialog(context);
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
WindowManager.LayoutParams lp = progDialog.getWindow().getAttributes();
lp.dimAmount = 0.7f;
progDialog.show();
Afterwards, I'm calculating something in the background
for()...
for()...
After the calculation is finished, I want to dismiss my dialog with
progDialog.dismiss();
However, this results in my dialog never being shown at all. When I remove the last line, the dialog is shown but is never dismissed. Is there a fix to it?
You better try with AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progDialog;
public YourAsyncTask(MyMainActivity activity) {
progDialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
progDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
#Override
protected void onPostExecute(Void result) {
// do UI work here
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}
Use the above code in your Main Activity. And, do your calculation part in doInBackground.
To set timer for your computation try below code:
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
Adding show/hide:
progDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
theLayout.setVisibility(View.GONE);
}
});
Update:
ProgressDialog class was deprecated as of API 26

Android function to AsyncTask

I am trying to create an AsyncTask for following function:
private void updateStreamImageRequest() {
countDownTimer = new CountDownTimer(10000, 2000) {
#Override
public void onTick(long millisUntilFinished) {
imageRequest();
}
#Override
public void onFinish() {
countDownTimer.start();
}
};
}
I do not have much knowledge in AsyncTaskand I am struggling to make it work. The AsyncTask shall continueally run a get request.
So far I have done this so far but it does not work:
public void getImgAsync() {
new requestAsyncTask();
}
public class requestAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
countDownTimer = new CountDownTimer(10000, 2000) {
#Override
public void onTick(long millisUntilFinished) {
API_StreamImage_Request();
}
#Override
public void onFinish() {
countDownTimer.start();
}
};
return null;
}
}
So do it this way -
Create your Countdown timer that runs for 10 seconds. So it will finish after 10 seconds. Then in finish method call your Asynctask to fetch in background.
countDownTimer = new CountDownTimer(10000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
new requestAsyncTask().execute();
}
};
countDownTimer.start();
class requestAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
countDownTimer.cancel();
countDownTimer.start();
}
#Override
protected Void doInBackground(Void... params) {
API_StreamImage_Request();
return null;
}
}
You might have to create a global variable of your countdown timer so that you can access it inside your asynctask class. Or you can even pass it as well if you want.
You can also use a Handler for this.
private int mInterval = 10000;
private Handler mHandler = new Handler();
Runnable requestCaller = new Runnable() {
#Override
public void run() {
try {
new requestAsyncTask().execute();
} finally {
mHandler.postDelayed(requestCaller, mInterval);
}
}
};
Or a Timer
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
new requestAsyncTask().execute();
}
},0, 10000);

Race condition with UI thread issue.

This is the code i am working on. Here I cant update the UI until myOnResponse is finished.Because we are doing a doInBackgrnd, so my textresponse is empty. And Since onPostExecute is happening right after.
For his I think PublicProgres should help.
How to Call PublishProgress at AsyncTask ?
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
action5(textResponse);
System.out.println(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}#Override protected void onPostExecute(String result) {
reply.setText(textResponse);
}
}
Please help.
I don't think that you have to use AsyncTask.
You can do something like this :
YourTask.java
public class YourTask implements Runnable {
private Handler handler;
private TextView textView;
public YourTask(TextView textView){
this.textView = textView;
handler = new Handler();
}
#Override
public void run() {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
#Override
public void run() {
if(textView != null){
textView.setText(textResponse);
}
}
});
}
#Override
public void onFailure(Exception e) {
}
});
}
}
And now how to use it :
SomeActivity.java
...
textView = (TextView) findViewById(R.id.textView);
...
Thread thread = new Thread(new YourTask(textView));
thread.start();
...
Nevertheless if you want to do this action in Asynktask just try this
private class ConversationTask extends AsyncTask<String, Void, Void> {
private Handler handler;
public ConversationTask(){
handler = new Handler();
}
#Override
protected Void doInBackground(String... params) {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
#Override
public void run() {
if(reply != null){
reply.setText(textResponse);
}
}
});
}
#Override
public void onFailure(Exception e) {
}
});
return null;
}
}
Hope it helps

Java AsyncTask not showing progress on UI though publishProgress(progress)

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.

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

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();

Categories

Resources