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
Related
i am trying to make the condition "when the dialog will be dismissed then auto play the video..." with the bellow code , i was accomplished to do that but the videoview doesnt auto play... can you suggest something?
mycode.java
final ProgressDialog progressDialog = new ProgressDialog(PlayVideo.this);
// Set progressbar title
progressDialog.setTitle("Please set the pyramid");
// Set progressbar message
progressDialog.setMessage("Loading...");
// Show progressbar
progressDialog.show();
// Find your VideoView in your video_main.xml layout
myVideoView = (VideoView) findViewById(R.id.video_view);
Uri uri = getIntent().getParcelableExtra("uri");
try {
myVideoView.setMediaController(mediaControls);
myVideoView.setVideoURI(uri);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
myVideoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
if(progressDialog.isShowing()) {
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progressDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
}
if (!progressDialog.isShowing()) {
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
}
else {
myVideoView.pause();
}
}
}
});
}
This will dismiss your dialog once the video is ready and play the video
if (progressDialog.isShowing()) {
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progressDialog.cancel();
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
myVideoView.pause();
}
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
}
I don't know why you are pausing. If you can explain what exactly is the flow that you are trying to implement then I can help better
I am making a app for training. In my app one video is playing after some second one alert dialog show the dialog contain question and answer student read the question and select the answer until my thread want to wait. Here i successfully get the video timing. I want to do pause the thread until alert dialog close.
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
running = true;
final int duration = mVideoView.getDuration();
new Thread(new Runnable() {
boolean myRunning;
public void run() {
synchronized (mSync) {
myRunning = mSync.running;
}
do {
textView.post(new Runnable() {
public void run() {
int time = Math.round(mVideoView.getCurrentPosition() / 1000);
textView.setText(time + "");
if (time == 5) {
running = false;
mVideoView.pause();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Page02.this);
alertDialogBuilder.setMessage("Are you sure,You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
onResume();
mVideoView.start();
arg0.dismiss();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!running) break;
}
while (mVideoView.getCurrentPosition() < duration);
}
}).start();
}
});
}
#Override
protected void onPause() {
super.onPause();
synchronized (mSync) {
running = false;// you can not set it here because
// it is possible for the thread to read it and exit the loop before he posts your message
mSync.mustBePost = true;
mSync.message = "Main Activity is going to pause";
}
}
#Override
protected void onResume() {
super.onResume();
threadNameCounter++;
synchronized (mSync) {
running = true;
mSync.mustBePost = true;
mSync.message = "Main Activity is going to resume";
}
t = new Thread("My Name is " + String.valueOf(threadNameCounter));
t.start();
}
}
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
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();
}
There is a ProgressDialog in my app. It is running but after finishing process does not close. Where is the error, I'm doing.
Thanks.
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
progressdialog.show();
new Thread(new Runnable() {
public void run() {
try {
// doing something...
progressdialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
do this......
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
progressdialog.show();
new Thread(new Runnable() {
public void run() {
try {
// doing something...
hm.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
Handler hm = new Handler()
{
public void handleMessage(Message msg)
{
progressdialog.dismiss();
}
}
Thanks.
progressdialog.setVisible(false);
if pricessdialog instanse of JDialog
Call progressdialog.dismiss(); from the main thread;
The right way of doing any work in background while showing the progress dialog is using AsyncTask with ProgressDialog bounded. See here. Remember, that you can not modify the UI from the thread, which is not UI thread.
The process dialog can also be dismissed by calling following method.
progressdialog.cancel();