Android progress dialog - android

My application fetches some html code from the internet and when done , displays it on the devices screen. Since it takes about 3-4 seconds to do that , in this time the screen stays black , I'd like to use a progress dialog. This is my code :
package com.nextlogic.golfnews;
// ALL THE IMPORTS ....
public class Activity1 extends Activity {
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
progressDialog = ProgressDialog.show(Activity1.this, "", "Loading...");
new Thread()
{
public void run()
{
try
{
sleep(2000);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
The program works but it doesn't display anything anymore. I have one error in logcat :
Only the original thread that created a view hierarchy can touch its views.
Could you please help me ? Thanks in advance.

The error is explicative enough. To update one visual object you must run the changes inside main thread. A quick and dirty fix could be calling the update code inside runOnUiThread().
However in your case I would use an AsyncTask to download and update the progress of the progress bar. The task has the property to run on UI thread when it ends (so you can update the views there, such as dismissing the progress dialog)
Here is an example how to use an AsyncTask to display a download progress dialog.
Update
Stackoverflow already has the answers to all your question. Here is an example of an AsyncTask to download some content and display the download progress. Just what you want.
Update 2
Ok here is your code using an AsyncTask:
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
new Thread()
{
#Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}
}

You need to do this way
runOnUiThread(new Runnable() {
public void run() {
// Do Your Stuff
}});

Dismiss your dialog like this:
Handler handler = new Handler();
handler.post(new Runnable(){
public void run(){
progressDialog.dismiss();
}
});

Create a UI thread after completing network operation
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});

The top answer works great, so here is an example to implement an AsyncTask in MonoDroid (thanks to Greg Shackels): http://mono-for-android.1047100.n5.nabble.com/AsyncTask-td4346647.html

Related

Struggling with upating my UI from Thread

I have tried AsyncTask, Handler, and a simple Thread to achieve what I am trying to do but I just cannot get any of them to work, below is the logic that I need to use to update my UI...
public class GameProcessor extends Thread {
#Override
public void run() {
for (Integer integer : sequence) {
//set button state to pressed
Console.getBottomLeft().getButton().setBackgroundResource(R.drawable.button_focused);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//set button state to un-pressed
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Please do not respond with, you cannot update the UI from anywhere but the main thread, I already know this and need a solution on how to loop through some values from the backend while updating the UI at the same time. From what I can tell, AsyncTask and Handler will not help much.
Any help will be very appreciated!
If you know about the UI thread, why don't you:
runOnUiThread(new Runnable() {
public void run() {
//set button state to un-pressed or pressed.. or whatever you want..
}
});
I don't understand your problem
Create a member Handler object in your Activity (mHandler). Whenever you want to update your UI from the other thread, call
mHandler.post(new Runnable(){
public void run(){
//update the button state
}
});
The Handler will call this run() method in the UI thread for you.
This is simplified. You will probably want to create your Runnables as member variables so your aren't recreating the same Runnables over and over.
If you want to loop through some valuse, while updating the UI at the same time, then you may consider using AsyncTask and may use this feature:
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
And from :
protected Long doInBackground(URL... urls) {
calculate value
publishProgress(value);
return totalSize;
}
This will keep on updating UI thread with intermediate values you send.
In case you already know this and have tried and it does not solve your purpose, am sorry :)
or you can try this:
public void run() {
Console.post(new Runnable() {
public void run() {
Console.getBottomLeft().getButton().setBackgroundResource(R.drawable.button_focused);
}
});
}
In order to update your UI thread you can use the handler. Here's a simple example of using AsyncTask and Handler:
private static final String MESSAGE_KEY = "com.example.mypackage.MSGKEY";
private static final int MESSAGE_AUTHENTICATING = 0;
private static final int MESSAGE_AUTHENTICATED = 1;
/**
* This handler will update UI
*
*/
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.getData().getInt(MESSAGE_KEY)) {
case MESSAGE_AUTHENTICATING:
hashstream_stream.setVisibility(View.GONE);
hashstream_progress.setVisibility(View.VISIBLE);
break;
case MESSAGE_AUTHENTICATED:
hashstream_stream.setVisibility(View.VISIBLE);
hashstream_progress.setVisibility(View.GONE);
break;
default:
break;
}
}
};
/**
* This method should be used to update UI thread.
*
* #param value
*/
private void postMessage(int value) {
Message msgObj = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt(MESSAGE_KEY, value);
msgObj.setData(bundle);
handler.sendMessage(msgObj);
}
/**
* AsyncTask Helper class as network op
*
*
*/
private class StreamHashTagTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//Do actual operation in here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
postMessage(MESSAGE_AUTHENTICATED);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
postMessage(MESSAGE_AUTHENTICATING);
}
/**
* If you need to update progress override onProgressUpdate() method.
* Since I am indeterminate using progress bar as authentication time
* cannot be calculated , I don't need update here
*/
}
Did you try?
instanceOfActivity.runOnUiThread(new Runnable(){
#Override
public void run() {
Console.getBottomLeft().getButton().setBackgroundResource(R.drawable.button_focused);
}
});
But in this case, I don't suggest you use an activity in another object.
Please using interface like above:
public interface INotifyChange {
void notify(object value); // Example: void notify(int progress);
}
In your activity where invoke GameProcessor
INotifychange mNotifier;
mNotifier = new INotifyChange() {
#Override
public void notify(object value) {
runOnUiThread(new Runnable(){
#Override
public void run() {
//You can update your UI here.
}
});
}
};
// And your GameProcessor
private INotifyChange mNotifier;
public GameProcessor(INotifyChange aNotifier) {
mNotifier = aNotifier;
}
// Where you want to update UI, please invoke
mNotifier.notify(value);

How to waits the thread till another thread completes

I want to show the progress dialog while loading the images in grid view.
The problem i'm facing was the current thread and Progress Dialog thread running simultaniously.
public String Method1(){
String output="";
final ProgressDialog aProgDialogL = ProgressDialog.show(this, "", "Loading...");
Thread thread = new Thread() {
public void run () {
//My codes
aHandlerL.post(new Runnable() {
#Override
public void run() {
//Post Runnable codes
aProgDialogL.dismiss();
}
});
}
};
thread.start();
/*
*
*
* OTHER CODES
*
*
*/
return output;
}
In the above example I need to run the code inside Progress Dialog Thread. After it finish executing i need to run my "OTHER CODES". How to do it?
.
I tried using Async task. Before async task completes method1 gets extcuted and reurning the string.
public String Method1(){
String result="";
new GetImages().execute();
return result;
}
public class GetData extends AsyncTask<Void, Void, Integer>{
#Override
protected void onPreExecute() {
aProgDialogL = ProgressDialog.show(Main.this, "", "Loading...");
}
#Override
protected Integer doInBackground(Void... params) {
//Progress Dialig Code
return null;
}
#Override
protected void onPostExecute(Integer result) {
aProgDialogL.dismiss();
//OTHER CODES
super.onPostExecute(result);
}
}
You can use Async task. http://developer.android.com/reference/android/os/AsyncTask.html. There is a good tutorial here. http://www.vogella.com/articles/AndroidPerformance/article.html.Also have a look at this link
http://developer.android.com/guide/components/processes-and-threads.html. Use asynctask modify it according to your needs.
doInBackground()- For long running operations. Don't update ui here.
onPreExecute()- update ui before running the operatio nin background.
onPostExecute()- update ui after running the operation.
I would suggest you to take somewhat different approach.
Dont involve any threads in Method1() function.Rather your Method1() function should be run under separate thread.
Below snippet will help you.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.btnPopup))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread() {
public void run() {
String answer = Method1();
runOnUiThread(new Runnable() {
#Override
public void run() {
// Here you will write the code which is
// to be executed on main thread.
}
});
};
}.start();
}
});
}
public String Method1() {
// Write code
return "result";
}
}
Instead of that : What about use Timer After specific Time Stop Your thread and and write your code you want after stop statement Like that :
Timer timer=new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
thread.stop;
// Other code }
}, Time You want );

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
}
}

Android Async task porgress bar doesn't comes until background process is completed

I am building a project in which i use async task to show progress bar.
I am using get() method to wait the main thread so we can do the other task before .
but progress bar is showing after completion of doInBackground thered.
I Want to show the loading bar when the loading starts.
It will dismiss when onPostExecute calls.
public class TempConverterActivity extends Activity {
pojo p;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
try {
new LoadData().execute().get();
} catch (Exception e) {
Log.e("async brix--", e.getMessage());
}
runned();
}
private void runned() {
ArrayList<String> al = p.getData();
for (String str : al){
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(TempConverterActivity.this);
protected void onPreExecute() {
dialog.setMessage("Loading data...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params) {
p = new pojo();
new SoapParser(p);
return null;
}
}}
Please help . Thanks in advance.
You can try following code,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
Edited: In my previous answer I suggested using a Handler; however, AsyncTask eliminates the need to do this which I didn't spot.
Why do you feel the need to call AsyncTask.get()? This is a blocking call, and you call this from the UI thread, thus it is ultimately a race condition as to whether it or onPreExecute() is run first.
I see no reason why you should call get() in this context. You want to call runned() after the AsyncTask completes, but you could do this by launching a new thread from onPostExecute(). Alternatively you could do as you do now, using get(), but call that from a new thread instead of the UI thread.

Android: How to work with background thread?

I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put all the code that fetches the content and displays it in a background thread and while the program is doing those functions , I would like to display a progress dialog. Could you help me do this ? I would like especially to learn how to put the code in a background thread.
MY CODE
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
new Thread()
{
#Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}
}
Check ASyncTask, its specifically created for such tasks.
public Runnable NameOfRunnable = new Runnable()
{
#Override
public void run()
{
while (true)
{
// TODO add code to refresh in background
try
{
Thread.sleep(1000);// sleeps 1 second
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
now start this with
Thread name = new Thread(NameOfRunnable);
name.start();
How to work with Background Thread.
Note: Do not work with UI with this background thread.
AsyncTask.execute(new Runnable() {
#Override
public void run() {
//TODO background code
}
});
Hope this would help you.

Categories

Resources