I would like to ask, If is there a better way to call a method in android multiple time.
But What I really want to know, is how to delay which showToas("Message 1"); call for 10 second and only after call the next.
Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
showToas("Message 1");
showToas("Message 2");
showToas("Message 3");
showToas("Message 4");
showToas("Message 5");
showToas("Message 6");
showToas("Message 7");
...
private void showToas(String message){
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
UPDATED
This is the away I managed to get it to work.
giving each method call a 5 sec break, But I think there most a be better way to implement this function ? Can you advice please. Thanks
private void CallMultipleToast(){
Runnable call_1 = new Runnable() {
#Override
public void run() {
Toast("Message one");
Runnable call_2 = new Runnable() {
#Override
public void run() {
Toast("Message two");
Runnable call_3 = new Runnable() {
#Override
public void run() {
Toast("Message three");
//CAN I ADD MORE
}
};//end call_3
new Handler().postDelayed(call_3, 5000);
}
};//end call_2
new Handler().postDelayed(call_2, 5000);
}
};//end call_1
new Handler().postDelayed(call_1, 5000);
}
try this way
Runnable r2=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showToas("Message 1");
}
};
new Handler().postDelayed(r2,1000);
do the same for others and increase Time Delay
You can use Timer for that:
//global variable counter
int counter = 1;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
showToas("Message "+counter);
counter++;
}
}, 0, 10000); //It will be repeated every 10 seconds
Hope this helps.
public class ToastShow {
private Context context;
private Toast toast = null;
public ToastShow(Context context) {
this.context = context;
}
public void toastShow(String text) {
if(toast == null)
{
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
else {
toast.setText(text);
}
toast.show();
}
}
and you can call toastShow(String text) many times it only changes the content of toast
runOnUiThread(new Runnable() {
public void run() {
try {
for(String str : array){
showToast(str);
Thread.sleep(10000L);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Related
I have a situation, I created a button and a function like this.
...
public void BtnOnClick(View view) {
displayMsg();
}
...
private void displayMsg(){
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "TestQueue", Toast.LENGTH_SHORT).show();
}
}, 3000);
}
...
If I click the button once a Toast should appear after a 3 seconds delay.
But if I quickly click the button two or more times then all the Toasts appear at the same time after 3 seconds without delay of 3 seconds between every Toast it's not good. I want a 3 seconds gap/delay between every Toast appearance despite of simultaneous clicks.
Is there any solution?
If there are multiple handlers in a queue then each handler delayed time start after the previous handler delay time end.
You can queue the requests to make sure the toasts are displayed at an interval.
ArrayList<Runnable> requests = new ArrayList<>;
bool inProgress = false;
private void displayMsg(){
Runnable runnable = new Runnable() {
#Override
public void run() {
Toast.makeText(this, "TestQueue", Toast.LENGTH_SHORT).show();
inProgress = false;
if (requests.size() > 0) {
handler.postDelayed(requests.remove(0), 3000 + Toast.LENGTH_SHORT);
}
}
}
if (!inProgress) {
inProgress = true;
handler.postDelayed(runnable, 3000);
} else {
requests.add(runnable);
}
}
Try this:
private final Handler handler = new Handler() {
final int DELAY = 3000;
final int DELAY_MSG = 1;
final Queue<Runnable> pendingRunnables = new ArrayDeque<>();
#Override
public void dispatchMessage(Message msg) {
if (msg.what == DELAY_MSG) {
final Runnable r = pendingRunnables.poll();
if (r != null) {
r.run();
sendEmptyMessageDelayed(DELAY_MSG, DELAY);
}
} else {
pendingRunnables.add(msg.getCallback());
if (!hasMessages(DELAY_MSG)) {
sendEmptyMessage(DELAY_MSG);
}
}
}
};
...
// post action
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "TestQueue", Toast.LENGTH_SHORT).show();
}
});
Maybe you can use postAtTime:
AtomicLong previous = new AtomicLong(System.currentTimeMillis());
private void displayMsg(){
handler.postAtTime(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "TestQueue", Toast.LENGTH_SHORT).show();
}
}, previous.updateAndGet(operand -> Long.max(operand + 3000, System.currentTimeMillis() + 3000)));
}
I've got this code:
#Override
public void onClick(View v) {
progressDoalog = new ProgressDialog(Hack.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDoalog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (progressDoalog.getProgress() <= progressDoalog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDoalog.incrementProgressBy(1);
}
};
});
}
}
Where can I add a code to open new activity when the ProgressDialog will be at 100%? Which and where exactly? Thanks for your help!
You can't start an Activity from a Dialog, but what you can do is start the Activity from the old one using a OnDismissListener.
Take a look at the documemtation :
https://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html
I haven't noticed but you can check the progress in your Handler, check if it's 100%, dismiss the dialog and start the new Activity, remember that you gotta do this on the UI thread
In my strings.xml I have 5 strings with text. And I want to be able to change the content of a TextView every 5 seconds.
Example:
First 5 seconds the TextView will show the content of the first string, then next five seconds it will show the second string. And after the fifth string it will show the first string again.
Sorry about this bad description, I'm new in Java.
Try this:
final TextView textView = yourTextView;
final int[] array = {R.string.text1, R.string.text2,R.string.text3,R.string.text4,R.string.text5};
textView.post(new Runnable() {
int i = 0;
#Override
public void run() {
textView.setText(array[i]);
i++;
if (i ==5)
i = 0;
textView.postDelayed(this, 5000);
}
});
new CountDownTimer(25000, 5000) {
public void onTick(long millisUntilFinished) {
mTextField.setText(//question here);
}
public void onFinish() {
mTextField.setText(//End of questions);
}
}.start();
For further Info see this -> http://developer.android.com/reference/android/os/CountDownTimer.html
You can use "Handler" in this
Create a handler in onCreate
`String[] arr = {R.string.value1, R.string.value2,R.string.value3,R.string.value4,R.string.value5};`
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
try {
Thread.sleep(5000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textView.setText(arr[i])
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
I have a task to run which takes a long time. So, I'd like to implement a progress dialog, spinning wheel, to show a message to users that the task is still running in the background. I found many solutions online and I used the following code. I ensured to run the task in separate thread. But it is not showing on UI.
OnClickListener confirmPrintButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
final SalesStockController salesStockController = new SalesStockController();
final ArrayList<ProductReload> productReloadList = reloadActivityAdapter
.getReloadList();
if (productReloadList.size() != 0) {
progressDialog = new ProgressDialog(StockReloadActivity.this);
progressDialog.setTitle("ABC Trading");
progressDialog.setMessage("Wait while loading...");
progressDialog.show();
new Thread(new Runnable() {
public void run()
{
// do the thing that takes a long time
try {
salesStockController.reload(productReloadList);
} catch (SQLiteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ABCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run()
{
progressDialog.dismiss();
}
});
}
}).start();
AlertDialog.Builder builder = new AlertDialog.Builder(
v.getContext());
builder.setCancelable(false).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
finish();
}
});
AlertDialog alert = builder.create();
alert.setTitle("ABC Trading");
alert.setMessage("Reload Successfully");
alert.show();
ReloadSlipPrint print = new ReloadSlipPrint(
productReloadList);
print.print();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
v.getContext());
builder.setCancelable(false).setPositiveButton("OK", null);
AlertDialog alert = builder.create();
alert.setTitle("ABC Trading");
alert.setMessage("No Stock To Reload");
alert.show();
}
} catch (Exception e) {
ABCUtil.displayErrorMsg(v.getContext(), e);
}
}
};
Can someone please point me out what is wrong with my code? Any help will be very much appreciated.
Just made up a simple example for you, you can try it.
public class MainActivity extends Activity {
private ProgressDialog mLoadingDialog;
private Handler mHandler = new Handler();
private void showLoadingDialog(final String title, final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
if(mLoadingDialog == null) {
mLoadingDialog = ProgressDialog.show(MainActivity.this, title, msg);
}
mLoadingDialog.setTitle(title);
mLoadingDialog.setMessage(msg);
}
});
}
private void hideLoadingDialog() {
mHandler.post(new Runnable() { //Make sure it happens in sequence after showLoadingDialog
#Override
public void run() {
if(mLoadingDialog != null) {
mLoadingDialog.dismiss();
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
#Override
public void run() {
showLoadingDialog("Loading", "Please wait...");
//DO something
hideLoadingDialog();
}
}.start();
}
}
You can use AsyncTask class to perform long runnning task
below is api link for the same
http://developer.android.com/reference/android/os/AsyncTask.html
Handler hnd = new Handler() {
#Override
public void handleMessage(Message msg) {
int id = sequence.get(msg.arg1);
if(msg.arg1 % 2 == 0) {
sq.get(id-1).setBackgroundResource(R.drawable.square_show);
} else {
sq.get(id-1).setBackgroundResource(R.drawable.square);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < sequence.size()-1; i++) {
record_tv.setText(""+i);
Thread.sleep(200);
Message msg = hnd.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch(Throwable t) {
}
}
});
background.start();
}
[CODE UPDATED] now it goes through the first loop and stops
do you have any idea why the code in the first runOnUiThread gets executed but it doesn't do what i want?
what i want is: change the image to "square", wait 2 seconds, change the image to "square_show", wait 2 secs and repeat the loop
i've been struggling for an hour now...
You can easily set image using following code.
sq.get(id-1).setImageResource(R.drawable.square_show);
sq.get(id-1).setImageResource(R.drawable.square);
public void show(int size) {
// CICLE THROUGH EACH SQUARE
for(int i = 0; i <= size-1; i++) {
Thread thrd = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id-1).setImageResource(R.drawable.square_show);
// System.out.println("1st..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sq.get(id-1).setImageResource(R.drawable.square);
// System.out.println("2nd..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thrd.start();
}
}
This is a wrong way to achieve it. This may help you.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation
I would suggest you to use a handler
int drawablebkg[] ={R.drawable.ic_launcher,R.drawable.icon};
Handler m_handler;
Runnable m_handlerTask ;
ImageView iv;
iv = (ImageView)findViewById(R.id.imageView1);
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
iv.setImageResource(android.R.color.transparent);
if(i<2)
{
ivsetBackgroundResource(drawablebkg[i]);
i++;
}
else
{
i=0;
}
m_handler.postDelayed(m_handlerTask, 2000);
}
};
m_handlerTask.run();
In onPause() of your activity
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//_t.cancel();
m_handler.removeCallbacks(m_handlerTask);
}
Another way
iv= (ImageView)findViewById(R.id.imageView1);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.ic_launcher), 2000);
iv.setImageResource(android.R.color.transparent);
animation.addFrame(getResources().getDrawable(R.drawable.icon), 2000);
animation.setOneShot(false);
iv.setBackgroundDrawable(animation);
//set setBackgroundDrawable(animation) is decprecreated i guess. not sure in which api
// start the animation!
animation.start();
Another way
Define background.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="#drawable/ic_launcher" android:duration="2000" />
<item android:drawable="#drawable/icon" android:duration="2000" />
</animation-list>
I your activity onCreate();
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setBackgroundResource(R.drawable.background);
AnimationDrawable animation= (AnimationDrawable)loadingRaven.getBackground();
loadingRaven.setImageResource(android.R.color.transparent);
animation.start();
Note to stop the animation you need to call animation.stop()
Because the resource changes in the UI thread and you are sleeping your background thread. The UI thread is running normally.
Use handlers:
public class MainActivity extends Activity {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 % 2 == 0) {
b.setBackgroundResource(R.drawable.analytic_icon);
} else {
b.setBackgroundResource(R.drawable.ic_launcher);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(2000);
Message msg = handler.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch (Throwable t) {
// just end the background thread
}
}
});
background.start();
}
}
Try this,It will work:
public void show(final int size) {
Thread thrd = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= size - 1; i++) {
id = (Integer) sequence.get(i);
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square_show);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thrd.start();
}