Run a thread in android after one thread completes its execution - android

I want run run a thread after one thread completes its execution.
Here I am using progress bar, after progress bar completes the method do1() should execute but when I am run the application the application force close.
here is my code..
public void onenc(View view) {
progressBar = new ProgressDialog(view.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Ecoding Text ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();
}
I have also tried AsyncTask but both run simultaneously.
Please help me I am a newbie in android.
Thanks in advance.
Update:
After AsyncTask
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
return null;
//Do Stuff
}
public void progressUpdate(Integer progress) {
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
#Override
protected void onPostExecute(Boolean result) {
//Call your next task
Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();
}
}
Now not even a single thread is executing the application force closes
After Another Update
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
return null;
//Do Stuff
}
public void progressUpdate(Integer progress) {
}
#Override
protected void onPostExecute(Boolean result) {
do1();
//Call your next task
/* Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();*/
}
}
Now the function do1() executes before progress bar completes.
Finally Solved it....Here is the answer.
Hope it will help others
class MyFirstTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.show();
}
#Override
protected String doInBackground(String... params) {
int i=0;
while(fileSize<100)
{
fileSize=fileSize+1;
publishProgress(""+(int)(fileSize));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publishProgress(""+(int)(fileSize));
return null;
}
public void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
progressBar.dismiss();
do1();
}
}

Don't use Thread() at all. Use AsyncTask as it makes life easier and implement the onPostExecute() method to call the next AsyncTask
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//Do Stuff that takes ages (background thread)
for(int i=0;i<100;i++){
doStuff();
Thread.sleep(1000L); //sleep because I'm just tired
publishProgress(i);
Thread.sleep(2000L); //sleep some more
}
}
#Override
public void progressUpdate(Integer progress) {
//Update progress bar (ui thread)
progressBar.setProgress(progress);
}
#Override
protected void onPostExecute(Boolean result) {
//Call your next task (ui thread)
new MyNextTask().execute();
}
Start your first task
new MyFirstTask().execute();

You can simply use join() method.
Thread first = new Thread();
Thread secThread =new Thread();
first.start();
first.join();
secThread.start();
but do not do this on main thread.

Related

ProgressDialog doesn't show a progress

I use a simple example of ProgressDialog usage. Author of this code sure that his code is right and works good.
ProgressDialog barProgressDialog;
Handler updateBarHandler;
public void launchBarDialog() {
barProgressDialog = new ProgressDialog(getActivity());
barProgressDialog.setTitle("Downloading Image ...");
barProgressDialog.setMessage("Download in progress ...");
barProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(20);
barProgressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
// Here you should write your time consuming task...
while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
Thread.sleep(2000);
updateBarHandler.post(new Runnable() {
public void run() {
barProgressDialog.incrementProgressBy(2);
}
});
if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
barProgressDialog.dismiss();
}
}
} catch (Exception e) {
}
}
}).start();
}
But when i run this code in my project, I see that ProgressDialog is always show a 0 value as a progress. What do i wrong?
Try the following code:
private ProgressDialog barProgressDialog;
public void launchBarDialog() {
barProgressDialog = new ProgressDialog(this);
barProgressDialog.setTitle("Downloading Image ...");
barProgressDialog.setMessage("Download in progress ...");
barProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(20);
barProgressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
// Here you should write your time consuming task...
while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
Thread.sleep(2000);
barProgressDialog.incrementProgressBy(2);
if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
barProgressDialog.dismiss();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Log.d("", BuildConfig.VERSION_NAME);
}

error on finish AsyncTask

After recieving a pictures from user, putting them in an array, animate() method is called from main, this method contains Asynktask. How can I finish this AsyncTask?
This is my code:
private void animate() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(pics[0]);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
while (true) {
try {
Thread.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(pics[pos]);
pos = (pos + 1);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}.execute();
}
From your code, I guess what you want is to change the image you show in an ImageView periodically. I'd suggest to change your code to use a Timer:
private Timer mTimer;
private void startCarousel(){
mTimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
// Your periodic task...
}
};
mTimer.schedule(timerTask, 1000, 500);
}
private void stopCarousel(){
if(mTimer != null){
mTimer.cancel();
mTimer.purge();
}
}

ImageView.Visible and ImageView.Gone is not working android

I have created code in that when I click on suppose A Image, then B Image should show for 100 Milliseconds and then goes off
I have done this by Java Code
public void changeRightDrum() {
System.out.println("RIGHT");
imageViewB.setVisibility(View.VISIBLE);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
imageViewB.setVisibility(View.GONE);
System.out.println("RIGHT DONE");
}
But it is not working B image is not displaying
Can anybody help me how to achieve that
You're blocking the UI thread with sleep() and any UI updates cannot really be performed.
Instead of sleeping, use a Handler with postDelayed() to schedule a Runnable to run after a delay.
Use postDelayed like this.
public void changeRightDrum() {
System.out.println("RIGHT");
imageViewB.setVisibility(View.VISIBLE);
imageViewB.postDelayed(new Runnable() {
#Override
public void run() {
imageViewB.setVisibility(View.GONE);
System.out.println("RIGHT DONE");
}
}, 100);
}
Implementing what #laalto said :
public void changeRightDrum() {
System.out.println("RIGHT");
imageViewB.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageViewB.setVisibility(View.GONE);
System.out.println("RIGHT DONE");
}
},200);
}
I have achieved by using this
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
imgPressedLeftTabla.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
imgPressedLeftTabla.setVisibility(View.GONE);
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();

Show Toast from a thread started in a broadcast receiver

I have a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.

how to stop this running thread?

public class MainActivity extends Activity implements Runnable{
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
ProgressBar linProgressBar;
private long fileSize = 0;
Thread t1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
linProgressBar.setProgress(0);
t1.interrupt();
}
});
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
basicInitializations();
}
});
}
public void basicInitializations(){
linProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
linProgressBar.setProgress(0);
linProgressBar.setMax(100);
try{
t1 = new Thread()
{
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
linProgressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
t1.start();
}catch (Exception e) {
}
}
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}else if (fileSize == 400000) {
return 40;
}else if (fileSize == 500000) {
return 50;
}
}
return 100;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
this is my main code and i could not stop this thread .
i want to stop it when i click the button b2(say cancel button).
the above code is not the original code and is a model , so please tell me how to stop that thread .
thankyou in advance . . . .
I have a alternate answer can try the same, inside your runnable loop always check a flag as run_flag, create it as a member variable and set it as true once you stared the loop, you can make it run_flag as false wenever you are done and at the same time you can set null to your thread also ... a safer way to come out through runnable loop and thread.
try{
t1 = new Thread()
{
public void run() {
while (progressBarStatus < 100 && run_flag == true) { // added run_flag here
// process some tasks
progressBarStatus = doSomeTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
linProgressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
t1.start();
}catch (Exception e) {
}
Your thread spends most of its time in Thread.sleep(), which is helpful. The thread pointer, t1, is a class member, which is also helpful. From your button handler, you can check to see if t1 is still alive and, if so, call t1.interrupt();. This will cause the thread's current sleep and future sleeps to throw the InterruptedException... now you just need to modify your exception handler to quit the thread in that case.

Categories

Resources