I want to show a Progress-Dialog before my view has been loaded.
First i wrote the code in onCreate() but the dialog doesn't appear in that case. So i wrote it in onResume() but in this case, it doesn't disappear even after the view has been loaded. can anyone tell whats going wrong here?
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dialog = ProgressDialog.show(this, "", "Please wait...", true);
//dialog.cancel();
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progressdialog
dialog.dismiss();
}
}.start();
citySelected.setText(fetchCity);
spinner.setSelection(getBG);
}
You cant update UI(which is in main UIthread) from other threads. If you want to run any query in the background, you can use AsyncTask.
In onPreExecute method, show dialog and onPostExecute you can dismiss the dialog.
If you want to use Thread, then update UI using handlers.
Using AsyncTask
public class MyAsyncTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
}
In Activity onCreate Method,
MyAsyncTask task = new MyAsyncTask();
task.execute();
better to use Asynctask ......... but if you still want same or want to know the solution only then can try
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
YourActivity.this.runOnUIThread(new Runnable(){
#Override
public void run(){
// dismiss the progressdialog
dialog.dismiss();
});
}
}.start();
You can use AsyncTask. It is better than Thread
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
Related
I am using a progress spinner on pre execute method of Async task to show it on UI and the data starts fetching in the background from Api using volley library.The problem is when it starts fetching the data,the loader stops spinning and its like the UI is not responding.
need help,Thanks in advance..
`
ProgressDialog dialog;
public void open() {
dialog = new ProgressDialog(BuzoongaContacts.this);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
dialog.setContentView(R.layout.progress_layout);
dialog.setCanceledOnTouchOutside(false);
}
public void stopLoading() {
Log.d("res", "stopLoading ");
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}`
Async Task:
class BuzoongaContactsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread( new Runnable() {
public void run() {
open();
}
});
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ContactsDataTableOperations conDataTab = new ContactsDataTableOperations(BuzoongaContacts.this);
conDataTab.open();
JSONParsingForContactsB.count = 0;
count = 0;
if (fromRefresh)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !",getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else
{
if (getContactsExistence() == 0) {
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else if (Constants.buzoongaContactsAdded)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else {
stopLoading();
}
}
arr_list = conDataTab.getAllRecords();
conDataTab.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
cb_select_all.setChecked(false);
iv_quick_launch.setBackgroundResource(R.drawable.quick_lounch_icon_disable);
Constants.selected_buzoonga_contacts = 0;
rl_delete.setAlpha(0.5f);
rl_delete.setClickable(false);
rl_show_contacts.setVisibility(View.INVISIBLE);
mAdapter.notifyDataSetChanged();
}
}
Basically, you can't touch your UI elements in background threads, which means that all your calls to startAnimation() or stopLoading should be wrapped with runOnUiThread.
But I can see your UI code is so bound up with your background code. Maybe you could consider using Thread & Handler instead of AsyncTask.
In my Activity, I load the content for a list from a DB, and want to display a ProgressDialog while it´s loading.
I got both working on it´s own, but if I load the data in a thread (which I should do?), the list is displayed before it´s data is loaded. But if I use join, the ProgressDialog doesnt even appear.
How can I combine this? Or is this not possible at all with threads? (AsyncTask maybe?)
Here´s the code for reference:
final ProgressDialog progressD=ProgressDialog.show(ShopSwitchActivity.this, "", "Loading..", true);
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
try
{
getData();
}catch(Exception e){}
}
});
myThread.start();
try {
myThread.join();
} catch (InterruptedException e) {
}
progressD.dismiss();
EDIT: Updated Code with AsyncTask:
public class LoadList extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
ShopSwitchActivity activity;
public LoadList(ShopSwitchActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
try{
activity.getData();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
return true;
}
}
Edit: My Solution
Using AsyncTask now to load the Data, and after it´s done, I refresh the list with the new data.
You can do it with AsyncTask. Write AsyncTask class in your main class that you want to do your operations. You can create the progress dialog in preexcecute of your async class and dismiss in onpostexecute of async class. Here is how you will do this:
class MyAsync extends AsyncTask<String, Void, Void> {
ProgressDialog pd;
Context co;
MyActivity ma;
public MyAsync (MyActivity ma){
this.ma= ma;
this.co = ma;
pd= new ProgressDialog(co);
}
#Override
protected void onPreExecute() {
this.pd.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your database operations here
return null;
}
#Override
protected void onPostExecute(Void result) {
// show db results and dismiss progress dialog pd.dismiss();
super.onPostExecute(result);
}
}
in MyActivity call as :
MyActivity ma = this;
new MyAsync(ma).execute();
You seem to miss the point of a thread. A thread occurs at the same time as your application. So your app doesn't call start then wait for the thread to be over- if it did you could just use a function. Instead your code continues to run. So if you just call join immediately, you're not doing anything. You'd get around a NetworkOnMainThreadException this way, but you'd still hold up the UI thread making your app totally non-responsive (and as a result not showing the dialog), and you'd eventually crash when a watchdog timer kills you.
Instead, the best way to handle this is to use an AsyncTask. Call getData in doInBackground(). Then dismiss the dialog in onPostExecute.
You should use AsyncTask instead actually.
Here is the link to the library. It is fairly simple:
1) onPreExecute() = show ProgressDialog
2) doInBackground() = execute your code
3) onPostExecute() = dismiss ProgressDialog
Here's a nice tutorial too.
In general:
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(this.context);
dialog.setMessage("Loading...");
dialog.setCanceledOnTouchOutside(false);
}
#Override
protected void onPostExecute(String result) {
if(dialog.isShowing()) {
dialog.dismiss();
}
}
private Thread myThread;
private ProgressDialog mProgDialog;
mProgDialog = ProgressDialog.show(ShopSwitchActivity.this,"","Laden..", true);
myThread= new Thread(new Runnable()
{
public void run()
{
myThread.setPriority(Thread.MIN_PRIORITY);
try
{
getData();
}catch(Exception e){}
runOnUiThread(new Runnable()
{
public void run()
{
if (mProgDialog != null&& mProgDialog.isShowing())
mProgDialog.dismiss();
} }
});
}
});
myThread.start();
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
}
}
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
}
}
I created a Progress bar but I can't see the loading animation. It's frozen. I want to display a progress bar when I click on the item and then see the bar working and not frozen. Here is my code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (((TextView) view).getText().equals("Zman-New (rus)")){
progDailog = ProgressDialog.show(testLoading.this, "Getting data", "Loading...",true,true);
new GetDataTask("stringurl.xml").execute();
}
Here is the getdata
private class GetDataTask extends AsyncTask<Void, Void, Integer> {
String url;
GetDataTask(String url){
this.url=url;
}
#Override
protected Integer doInBackground(Void... params) {
//do all your backgroundtasks
intent = new Intent(rusNewsP.testLoading.this, rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
return 1;
}
#Override
protected void onPostExecute(Integer result) {
//finish up ( or close the progressbar )
//do something with the result
progDailog.dismiss();
super.onPostExecute(result);
}
}
If you just want to test Progress try this:
private class Initialize extends AsyncTask<Short, Short, Short> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(yourlass.this);
pd.setMessage("test");
pd.show();
super.onPreExecute();
}
#Override
protected Short doInBackground(Short... params) {
try {
synchronized (this) {
wait(2000);
}
} catch (InterruptedException ex) {
}
return null;
}
#Override
protected void onPostExecute(Short result) {
pd.dismiss();
super.onPostExecute(result);
}
}
And don't call startActivity in the doInBackground-Method. Call it in OnPostExecute instead. GUI Operations should not be done in doInBackground.
Try to start the Activity Direct from the UI thread as that will be fast.
Still,if you want this way then try to start it from the onPostExecute Method.
Not from the doInBackground.
protected void onPostExecute(Integer result)
{
//do something with the result
progDailog.dismiss();
intent=new Intent(rusNewsP.testLoading.this,rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
}
And...don't call super.onPostExecute(result); after dismissing the progressDialog..after completing the doInBackground(Short... params),It will return directly to onPostExecute Method where it will dismiss the ProgressDialog first time and then execute the Constructor which will try again to dismiss the ProgressDialog which is already dismissed resulting into uncaught exception.