Show Dialog After Thread is Finish - android

I want show dialog after finish Thread.
In thread I am changing TextView's Value like as 0 to 100...
When TextView Value is reach 100 then i want to show dialog..
What i do for it.
Thanks in advance...
Code Snippet:
final Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
synchronized (this)
{
try
{
for(int i=0 ; i<speed; i++)
{
final int value=i+1;
wait(3000/speed);
Test.this.runOnUiThread(new Runnable() {#Override public void run()
{
accText.setText(String.valueOf(value));
}});
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread.start();
this is asyntask code snippet...
class setTextBackgroundTask extends AsyncTask<String , Integer, Void>
{
#Override
protected void onPreExecute()
{
}
#Override
protected Void doInBackground(String... params)
{
Thread th = new Thread();
int value;
for(int i=0 ; i<speed; i++)
{
value=i+1;
publishProgress(value);
try {
th.sleep(3000/speed);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
accText.setText(String.valueOf(values[0]));
System.out.println("Value=="+values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result)
{
showShareDialog();
}
}

This document explains how you can create dialogs.
Please note that you will have to do any dialog creation code on the UI thread.
You already have code that runs something on the UI thread, just do that outside the loop,but with the dialog creation code inside.

You should use AsyncTask: subclass AsyncTask, override doInBackground() to execute your time consuming action on another thread, and then override onPostExecute() to show your dialog.
Note that you cannot change UI elements from a non-UI (background) thread. AsyncTask takes care of that for you: it calls doInBackground() on a new thread and then calls onPostExecute() on the UI thread as soon as the background task is complete.

Related

How to make a image visible after completion of Thread?

I am making a project in which i am using the progressdialog and i want to show this progress dialog on creation of activity and i am able to that. In the on create method i want the image to be invisible and i want image to be visible after completion of progress dialog but it is throwing exception in the line imagevisible();
The logcat is:
04-12 12:48:35.309: E/AndroidRuntime(4994): at com.example.project1.ShowPassword$waiter.run(ShowPassword.java:59)
Code
ImageView iv;
ProgressDialog p;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showpass);
iv=(ImageView)findViewById(R.id.imageView1);
iv.setVisibility(View.INVISIBLE);
p= new ProgressDialog(this);
p.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
p.setTitle("Getting Password: ");
p.setMessage("Loading:");
p.setMax(100);
p.show();
Thread t=new Thread(new waiter());
t.start();
public class waiter extends Thread{
public void run(){
for(int i=0; i<5; i++){
p.incrementProgressBy(20);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}p.dismiss();
imagevisible();
}
}
public void imagevisible(){
iv.setVisibility(View.VISIBLE);
}
You can't change UI from non UI thread. You can use runOnUiThread method of Activity:
public class waiter extends Thread{
public void run(){
//...
runOnUiThread(new Runnable() {
#Override
public void run() {
imagevisible();
}
});
}
}
What you want is an AsyncTask. Implement doInBackground() (runs in the background) and onPostExecute() (runs on the UI thread).
https://developer.android.com/reference/android/os/AsyncTask.html

How to hide imageview after some intervals android

I am working on an android app in which i want to hide my image view after some interval. i am using this code but it is not hiding. can anybody tell me how i can hide it ???
showtrue1.setBackgroundResource(R.drawable.ticktrue);
showtrue1.setVisibility(View.VISIBLE);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
showtrue1.setVisibility(View.GONE);
Try CountDownTimer:
new CountDownTimer(1000, 100) {
public void onTick(long millisUntilFinished) {
// implement whatever you want for every tick
}
public void onFinish() {
showtrue1.setVisibility(View.GONE);
}
}.start();
You can use async Task also to solve your problem . In its backgound function make a thread sleep for particular second and in the post method make trhe visibility gone for your image viiew.
Call the execute method in your oncreate
new MyAsyncTask().execute();
and make an inner class as defined below:
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
// show your progress dialog
showtrue1.setBackgroundResource(R.drawable.ticktrue);
showtrue1.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void params)
{
showtrue1.setVisibility(View.GONE);
}
}
Create a separate thread that sleeps for 1 seconds then call runOnUiThread to hide the view.
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do some stuff
showtrue1.setVisibility(View.GONE);
}
});
}
};

How to update view after done with the progress bar?

CASE: I have a button and list-view in the activity. On click of the button I have added a click listener, which starts a new thread in which I update the progress bar. After the job is done i.e. progress bar is done 100%, I want to update the list-view.
final OnClickListener mStartScan = new OnClickListener() {
#Override
public void onClick(View v) {
// prepare for a progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(false);
progressBar.setMessage(getString(R.string.text_scanning_inbox));
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(totalSms);
progressBar.show();
progressBarStatus = 0;
Thread progressThread = new Thread(new Runnable() {
public void run() {
while (progressBarStatus < totalSms) {
// process some tasks
progressBarStatus = someStuff();
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= done) {
// sleep 1 seconds, so that you can see the 100%
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
// this method updates the list
populateList();
}
}
});
progressThread.start();
// try {
// progressThread.join();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } finally {
// populateList();
// }
}
};
PROBLEM: When I update the listview after completion of the task and dismissing progress bar, I get an exception which says that the view can be updated only from the thread in which it is created.
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
WHAT ELSE I TRIED: I tried waiting for the thread which is running progress bar to complete and then update listview from the main thread.
try {
progressThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
populateList();
}
However, this does not work. It does not show the progress bar at all.
I used this:
private ProgressDialog progressBar;
class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(getApplicationContext());
progressBar.setMessage("please, waiting ...");
progressBar.setCancelable(false);
progressBar.show();
}
#Override
protected String doInBackground(String... params) {
try {
// get info and set them in my model ...
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != progressBar && progressBar.isShowing()) {
progressBar.dismiss();
}
// do work in UI and set info adapter and refresh list ...
populateList();
myListView.invalidateViews();
}
}
for more information:
http://developer.android.com/reference/android/widget/ArrayAdapter.html#notifyDataSetChanged%28%29
Only the original thread that created a view hierarchy can touch its views.
Here original thread refers to the ui thread. You are attempting to update ui inside a thread which is not possible.
You cannot update ui from the back ground thread. You can use runOnUiThread .
runOnUiThread(new Runnable() //run on ui threa
{
public void run()
{
}
});
I would suggest you to use asynctask
You use use asynctask for this purpose. The onPreExecute(), onPostExecute() are invoked on the ui thread and you can use the same to update ui. You can do your background computation in doInbackground()
http://developer.android.com/reference/android/os/AsyncTask.html
Check the topic under heading The 4 steps.
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// background computation and publish progress
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// update progress bar
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// cancel the progress bar
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//display progress bar
}
}
Load asynctask on the ui thread
new TheTask().execute().
The error you are receiving is because of the fact that you are trying to change the UI components on a secondary thread. You should read this for more information on how to use threads on Android.
You can use the Activity method runOnUIThread() to call the populateList() method or whatever makes the updates on the UI(main) thread. If you read the doc mentioned above, you will find out more about this.

How to sync between ProgressDialog and text appearance?

i got this progress dialog code:
new Thread() {
#Override
public void run() {
try {
sleep(1000);
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
progressDialog.dismiss();
}
}.start();
and i got text that will apear after some httprequest actions:
editText2.setText(stringEr);
how do i sync between them? i want that the text will be hidden untill the progress will finish
tnx!
You have to use Handlers to update your UI. A little modification here,
new Thread()
{
#Override
public void run()
{
try
{
//Instead of sleep, call your http request method here.
handler.sendEmptyMessage(0);
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
progressDialog.dismiss();
}
}.start();
And create a handler in onCreate(),
Handler handler=new Handler()
{
public void handleMEssage(Message msg)
{
if(msg.what==0)
editText2.setText(stringEr);
}
};
i think you should use AsyncTask for that and you can hide in OnPreExecute Method i mean when asynctask in started and show in OnPostExecute method. after complete the progress.
Android skip the painful Threading concept, Use Asyntask class.
http://developer.android.com/reference/android/os/AsyncTask.html
private class UIOperation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
//show dialog
}
#Override
protected String doInBackground(String... params) {
//collect data
return null;
}
#Override
protected void onPostExecute(String result) {
//dismiss dialog
//update UI
}
}

progress Dialog simpel

i want to add a progress Dialog button when i click on this button before the new activity apperar, i think i don't need a thread, i did search but i find only that i need to do a thread and many other think it s not clear
i just want when i clik on a progress Dialog say to the user to wait so a few sec the other activity will appear that's all:
btn_newsfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(), CustomizedListView.class);
startActivity(i);
}
});
There are three different different ways in which you can use a ProgressDailog -using threads, handlers and async tasks.
here a example of async task for using a progress Dialog
private class Operation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params)
{
// code to be executed in background thread
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// runs on UI thread and updated UI after executing doInBackground
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Title ", "Loading...");
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
// runs on UI thread and starts first
}
}

Categories

Resources