I want to make a Toast appear and THEN let a sleep operate.
If i do that, the Toast appears AFTER the sleep, but i want it the other way around. Anyone has a suggestion? Here my code for this
switch (checkedRadioButton) {
case R.id.radio0 : radioButtonSelected = "radiobutton1";
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG).show();
vd.vibrate(100);
android.os.SystemClock.sleep(1000);
vd.vibrate(100);
thanks so far
The display of toast is an asynchronous (i.e not a blocking call) operation, means once the toast request is executed, the operating system jumps to the next operation and meanwhile the toast is prepared and displayed.
To acquire your default behavior, you should execute the thread-sleep call after few seconds of delay. Use a Handler and its postDelay method for this.
Delay time should be like:
LONG_DELAY = 3500; // 3.5 seconds
SHORT_DELAY = 2000; // 2 seconds
Try to use AsyncTask class.Write this code as it is. no need to take the name of variable of class AsyncTask.
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPostExecute(Void result) {
Toast toast2 = Toast.makeText(context, "Task completed",
Toast.LENGTH_SHORT);
toast2.show();
}
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "here is your text before Sleep", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(1000); // time in milisec 1000ms= 1sec
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}.execute();
Related
I want to populate a list after toast is disappear
I have a multiprocessing thing and in one method more around 10 toast is shown after doing something, i want to show in the list what is done what is not processed.
My problem is program runs at once and list will be populated as well. I want to show toast as it takes some delay than update list
Creating a Thread that lasts as long as the Toast is displayed and then you can do your work.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// your other stuff
Toast.makeText(this,"This is a Toast", Toast.LENGTH_LONG).show();
thread.start();
}
Now create a thread that waits for (LENGTH_LONG = 3.5) or (LENGTH_SHORT = 2) seconds
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(3500); // As I am using LENGTH_LONG in Toast
Your_Activity.this.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
I am trying to cancel a log run AsyncTask if a certain period of time exceeds (if AsyncTask is not automatically finised)
Below is the code where I setup my task to start with timeout
final ProfileDesc pdsc = new ProfileDesc();
pdsc.execute();
Thread th_pdsc = new Thread(){
public void run()
{
try{
pdsc.get(120000, TimeUnit.MILLISECONDS);
}
catch(Exception e){
pdsc.cancel(true);
((Activity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Download Time out. Please Try again later.", Toast.LENGTH_LONG).show();
}
});
}
}
};
th_pdsc.start();
below is the code for my AsynTask
private class ProfileDesc extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Header Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
protected void onPostExecute(Void params) {
super.onPostExecute(params);
dialogue.dismiss();
}
protected Void doInBackground(Void... arg0) {
//long run work
return null;
}
}
After two minutes it's still running. How can I set up the time out? Note: I have followed this link of Stack Overflow for this code.
What you had
ProfileDesc pdsc = new ProfileDesc();
pdsc.execute();
was enough. There is no need for a Thread. doInBackground is invoked on the background thread. So you can do you Network operations in doInbackgorund.
Secondly calling get makes AsyncTask no more Asynchronous as it blocks the ui thread
get(long timeout, TimeUnit unit) Waits if necessary for at most the
given time for the computation to complete, and then retrieves its
result
I guess you have misunderstood the use of Asynctask. Read the docs
http://developer.android.com/reference/android/os/AsyncTask.html
You may want to check this
Stop AsyncTask doInBackground method
Here new thread is not needed.Just remove "dialogue.setIndeterminate(true)". It means the "loading amount" is not measured.I think it's creating the problem.
I'm new to Android development. I've be working on Swing and SWT for several years. Both Swing and SWT has a stratage to execute code in UI thread sync and async. The typical usage is doing some time-consume staff in one thread then display the result in UI thread async.
So my question is, is there similiar stratage in Android? Here is my code. Parameter runnable is some time-consume code. This method will display a waiting dialog during the execution then EXPECT to show a Toast after it is finished. But the Toast need to be show in UI thread. So how to do that?
public static void showWaitingDialog(final Activity parent, final Runnable runnable, String msg) {
if (StringUtils.isEmpty(msg)) {
msg = "processing...";
}
final ProgressDialog waitingDialog = ProgressDialog.show(parent, "Please Wait...", msg, true);
// execute in a new thread instead of UI thread
ThreadPoolUtil.execute(new Runnable() {
public void run() {
try {
// some time-consume operation
runnable.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
waitingDialog.dismiss();
}
// TODO: How to display a Toast message here? execute some code in UI Thread.
}
});
}
And is there some words about Android UI system? Such as is it Thread-Safe, how thread works together and so on. Many Thanks!
There are several ways for doing that,
AsyncTask -
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers. Example for using AsyncTask
Service -
A Service is an application component representing either an
application's desire to perform a longer-running operation while not
interacting with the user or to supply functionality for other
applications to use. Example for Using Service.
IntentService -
IntentService is a base class for Services that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through startService(Intent) calls; the service is started as needed,
handles each Intent in turn using a worker thread, and stops itself
when it runs out of work. Example for using IntentService.
You can use AsyncTask like this.
To call AsyncTask
new getAsynctask().execute("");
and here is the class for geting result.
class getAsynctask extends AsyncTask<String, Long, Integer> {
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Pass.this, null, "Please wait...");
}
protected Integer doInBackground(String... params) {
try {
// do your coding
return null;
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
try {
if (loading != null && loading.isShowing())
loading.dismiss();
} catch (Throwable t) {
Log.v("this is praki", "loading.dismiss() problem", t);
}
}
}
Whenever you are working with Separate thread which is not your UI thread the best way is to use Handler. Whenever you want to intimate user from your Thread, suppose a progress then send a message to Handler to so. Inside Handler you can handle message and write a code snippet to Change anything on UI. This is the preferred way for Android. see these link1 , link2 & link3
You use this AsynTask as a inner class of your activity. In do in background do the time consuming task you want to do and then in on postexecute you can show the text message.
call this from your main activity
initTask = new InitTask();
initTask.execute(this);
protected class InitTask extends AsyncTask<Context, Integer, String> {
#Override
protected String doInBackground(Context... params) {
// Do the time comsuming task here
return "COMPLETE!";
}
// -- gets called just before thread begins
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// -- called from the publish progress
// -- notice that the datatype of the second param gets passed to this
// method
#Override
protected void onProgressUpdate(Integer... values) {
}
// -- called if the cancel button is pressed
#Override
protected void onCancelled() {
super.onCancelled();
}
// -- called as soon as doInBackground method completes
// -- notice that the third param gets passed to this method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Show the toast message here
}
}
Use a handler:
static final int SHOW_TOAST = 0;
public static void showWaitingDialog(final Activity parent, final Runnable runnable, String msg) {
if (StringUtils.isEmpty(msg)) {
msg = "processing...";
}
final ProgressDialog waitingDialog = ProgressDialog.show(parent, "Please Wait...", msg, true);
// execute in a new thread instead of UI thread
ThreadPoolUtil.execute(new Runnable() {
public void run() {
try {
// some time-consume operation
runnable.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
waitingDialog.dismiss();
}
handler.sendMessage(handler.obtainMessage(SHOW_TOAST));
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_TOAST:
//Toast here
break;
}
}
};
The Painless threading article from the android developer resources provides different alternatives depending on the specific SDK version.
I need to display user info while app processing some data. I use ProgressDialog like
pd = ProgressDialog.show(MainActivity.this,
"", "Processing",
true, false);
Processing takes while connect to network and download data, but when network is not available it returns immediately and my progress dialog just flash very quick. Is there maybe more elegant solution then to put in catch Thread to sleep for some time :
try{
//connecting and calculating
}
catch(Exception exc){
Thread.sleep(400);
handler.sendEmptyMessage(0);
}
I need to set minimal time for my ProgressDialog regardless of success or failure ? Does anybody know how to achieve that ?
This will help you
Write the following code immediately after the dialog initialization
new Thread(){
public void run(){
try{
Thread.sleep(5000);
}
catch(Exception ex){}
try{
Message msg=actHandler.obtainMessage();
actHandler.sendMessage(msg);
}
catch(NullPointerException ex){
Log.e("Handler Exception :",ex.toString());
dialog.dismiss();
}
}
}.start();
actHandler=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
doSomthing();
}
};
public void doSomething(){
dialog.dismiss();
}
I would do this the other way around: only show your progressDialog if you can establish the connexion. I feel that making the user wait 0.4 second for a result you already know just for the bling is pointless ;)
In my app i m trying to fetch data from server and storing in database.
When it is doing all these work i want at that time progressdialog should show, if successfully data fetches then dialog should close and some alertDialog should show for msg "successfully data fetched". and if any n/w problem there, then it should show different msg that "problem with n/w".
for that i am doing like below,
public void onClick(View arg0) {
myProgressDialog = ProgressDialog.show(
getParent(), "Please wait...",
"Doing upgrade...", true);
new Thread() {
public void run() {
try {
upgradeAll();//function where data fetched from server
sleep(5000);
} catch (Exception e) {
}
// Dismiss the Dialog
myProgressDialog.dismiss();
Toast.makeText(UpgradeAllTableData.this, "Due to some internal problem \n" +
"it couldnot update..", Toast.LENGTH_LONG).show();
}
}.start();
}
AsyncTask code,
private class UpgradeTask extends AsyncTask<Context, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(UpgradeAllTableData.this);
#Override
protected void onPreExecute() {
System.out.println("In onPreExecute ");
Dialog.setTitle("Loading");
Dialog.setMessage("Please wait for few seconds...");
Dialog.show();
}
#Override
protected Void doInBackground(Context... params) {
System.out.println("In doInBackground ");
upgradeAll();
System.out.println("In doInBackground after fetching");
return null;
}
#Override
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
Dialog.dismiss();
Toast.makeText(UpgradeAllTableData.this, "Problem with internet" , Toast.LENGTH_SHORT).show();
alertboxNeutral("Warning", "Problem with Internet Connection", "Okay","Try again");
}
}
Problem is Toast is not showing. why?
My question is which condition and where to give so that if any problem with n/w then it show some msg and success then show another msg.
Where i should write code for that?
Give me some suggestion.
Thank you
Not exactly an answer to your particular question, but have you considered AsyncTask? It's pretty much designed to handle situations like yours, where a task is performed async while showing some progress (and eventual result) on the UI thread. Alternativelly, you could broadcast an intent and have your activity catch it to show the toast, since your Toast should be show from your UI thread as well.
update:
AsyncTask reference - http://developer.android.com/reference/android/os/AsyncTask.html
What you are doing is totally wrong. UI thread handles all UI changes, but here you are creating ProgressDialog in UI thread and dismissing it in some Other Thread.. A solution is make use of AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html