Unable to close Progress Dialog in Android - java

I want to create a progress dialog in android, keep it open for 2 seconds then close it.
Below is the code I have written:
package com.example.proressdialogtest;
import android.app.activity;
import android.app.ProgressDialog;
import android.os.bundle;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ProgressDialog pg = new ProgressDialog(MainActivity.this, 4);
pg.show(MainActivity.this, null, "Searching...", false);
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
pg.dismiss();
}
When I run the code on my device, the ProgressDialog is opened and then it stays open, it does not close after 2 seconds. What am I doing wrong?
As per the answers below. I have added the onPreExecute() and onPostExecute() methods before and after the doInBackground method respectively.
Here is the code for the two methods.
ProgressDialog pd;
public void onPreExceute() {
pd = new ProgressDialog(MainActivity.this);
pd.show(MainActivity.this, "", "Searching...", false);
}
public void onPostExecute() {
pd.dismiss();
}
The problem still persists. The progress bar will not close.

You are calling sleep() on the UI Thread. Don't do this. Use runOnUiThread or an AsyncTask
Painless Threading
AsyncTask
I would use an AsyncTask. You will start the ProgressDialog in onPreExecute() then close it in onPostExecute(). It is a UI element so using it in doInBackground() will give you the error
This SO answer has a good example of using it

Edit:
Use this code
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final ProgressDialog pg ;
pg = ProgressDialog.show(MainActivity.this, null, "Searching...", false);
Thread timer=new Thread(){
public void run()
{
try {
sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
finally{
pg.dismiss();
}
}
};
timer.start();
}
}
You are pausing the UI thread by calling
Thread.sleep(2000);
Because Thread.sleep(x) will make the current thread sleep for x milli seconds
which is bad thing.
place
I don't know why
pg.dismiss() in finally block to make sure that progress dialog will be closed.
And also your Code won't run because you have missed
super.onCreate(savedInstanceState);

following code will work for you,
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog = null;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(MainActivity.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
}
}.execute();

Related

Get AsyncTask's result without blocking the thread

I have the code that sends requests to REST API in AsyncTask.
Also, I have a ProgressDialog initialization in preExecute() and its dismission in postExecute().
I want ProgressDialog to show an indeterminate spinner (you know, that loading animation), but I need to get a result too. get() blocks the main thread where I'm invoking it in - what's the workaround for that case?
Main thread (main activity)
LoginTask task_login = new LoginTask();
AsyncTask<String, Void, JSONObject> response = task_login.execute(et_username.getText().toString(), et_password.getText().toString());
try {
JSONObject json = response.get();
Toast.makeText(MainActivity.this, json.toString(), Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
Toast.makeText(MainActivity.this, "Interrupted.", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
AsyncTask (dummy doInBackground):
public class LoginTask extends AsyncTask<String, Void, JSONObject> {
private LoginTask self = this;
private ProgressDialog progressDialog;
#Override
protected JSONObject doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.context,
"Logging in...", "");
progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
MainActivity.context.getResources().getResourceEntryName(R.string.dialog_button_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
self.cancel(true);
}
});
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.dismiss();
}
}
You can use AsyncTask's onProgressUpdate() method to perform the actions on the UI thread (such as showing or updating a loading animation) while doInBackGround() does the background work on another thread.
Basically you invoke the publishProgress() method from within doInBackGround(), which in turn calls onProgressUpdate().
Check out the Android reference page on AsyncTask for an example.
Please look at the usage of AsyncTask https://developer.android.com/reference/android/os/AsyncTask#usage
There is a callback function onPostExecute which returns (as parameter) the value you requested:
private class RestTask extends AsyncTask<Object, Object, String> {
protected String doInBackground(Object... args) {
// this happend on background thread
return downloadData();
}
protected void onPreExecute() {
// this happend on UI thread
showSpinner();
}
protected void onPostExecute(String result) {
// this happend on UI thread
hideSpinner();
doSomethingWithDownloadResult(result);
}
}
Usage:
new RestTask().execute()
As you edited the question, this:
try {
JSONObject json = response.get();
Toast.makeText(MainActivity.this, json.toString(), Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
Toast.makeText(MainActivity.this, "Interrupted.", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
should be called in previous Tasks onPostExecute method, this way you will not block you UI with get method waiting on login result.
1 - You can use a callback method.
but keep in mind you should call it in your main thread.
2 - you can use LocalBroadcastManager in order to send your result through Intent.
3 - you might want to use in application messaging libraries which are more reliable in my opinion. one example which I use very often is EventBus.

How to change progressDialog text

i have an asynctask but if i implement a Thread.Sleep , then my app crashes , i dont know why, in onPreExecute i can see my first message and then after two secs it appears the other one i put in doInBackground , but its not working
private class sendMail extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialog.setMessage("Please wait...");
dialog.show();
}
// automatically done on worker thread (separate from UI thread)
#Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.setMessage("Downloading files...");
new BackgroundTask().execute();
//MY DOWNLOADING METHODS STUFF
And then i dismiss this dialog somewhere else
Log
An error occurred while executing doInBackground()
You cannot access the UI elements from a background thread you can update the progressbar in onProgressUpdate, most importantly you need to publishProgress(value) in doInBackground and update using onProgressUpdate. Read more about the AsyncTask here.
Example code:
class MyTask extends AsyncTask<Integer, Integer, String> {
#Override
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
txt.setText(result);
btn.setText("Restart");
}
#Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
#Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setMessage("Downloading files...");
progressBar.setProgress(values[0]);
}
}
Use UI thread to show dialog message in doInBackground refer this https://stackoverflow.com/a/15757788/6626966

Issues In Splash Screen with progressDialog

My Issue is progress Dialog not display with the splash Screen?Can Any one solve this, Any help could be appreciated thanks in advance !
public class Splash extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
Thread thread = new Thread(){
#Override
public void run() {
try
{
sleep(3*1000);
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
}catch (Exception e)
{
e.printStackTrace();
}finally {
Intent i = new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
};thread.start();
}
}
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
Thread thread = new Thread(){
#Override
public void run() {
try
{
sleep(3*1000);
}catch (Exception e)
{
e.printStackTrace();
}finally {
progressDialog.dismiss();
Intent i = new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
};thread.start();
}
}
Cuz you are updating the UI in background thread..
try to use the
runOnUiThread(new Runnable.......)
or try to put the UI work on UI thread.
Everthing you write inside a thread will be executed in background. you can't manipulate any UI elements from a background Thread. you should be getting an error from this code, check your stacktrace. I suggest you remove the code for the ProgressDialog from the Thread and put it before the Thread.
You should show the progress dialog from UI thread. Or you can use runOnUiThread(...) method. If you have to show it from a different thread write thin inside run method of thread:
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
//add try catch
sleep(3*1000);
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
I would suggest using handlers instead of sleep in your activity. You can also try this without the thread in your code:
Handler h = new Handler(Looper.getMainLooper())
h.postDelayed( new Runnable() {
#Override
public void run() {
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
},
(3*1000));

Showing dialog box in android

I know this is duplicate but trust me i have tried many of the available codes and still not getting this worked.
Below are my code
public class LookIn extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
//Initializing properties
}
public void onClick(View v) {
// Event for button click
callHelper();
}
private void callHelper()
{
List result=null;
try {
String jsonResponse=new CallmeGetHelperAsyncTask(this).execute(params).get();
result= RestUtil.getUserList(jsonResponse);
}
catch (InterruptedException e) {
Log.e("Callme", Log.getStackTraceString(e));
} catch (ExecutionException e) {
Log.e("Callme", Log.getStackTraceString(e));
}
catch(JSONException x)
{
Log.e("Callme",Log.getStackTraceString(x) );
}
}
}
Below is my AsyncTask class
public class CallmeGetHelperAsyncTask extends AsyncTask<String,Void,String > {
private AppCompatActivity activity=null;
private ProgressDialog dialog=null;
public CallmeGetHelperAsyncTask(){}
public CallmeGetHelperAsyncTask(AppCompatActivity activity){
this.activity=activity;
//this.dialog= dialog;
}
#Override
protected void onPreExecute() {
if(this.dialog!=null)
{
Log.v("Callme", "Starting Dialog");
dialog = ProgressDialog.show(this.activity, "title", "message");
// this.dialog.setMessage("Looking for Helpers");
this.dialog.show();
}
else
{
dialog = ProgressDialog.show(this.activity, "title", "message");
}
}
#Override
protected void onPostExecute(String s) {
if(this.dialog!=null)
{
Log.v("Callme","Closing Dialog");
this.dialog.dismiss();
}
else
{
Log.v("Callme","Dialog is not initiated in CallmeGethelperAsyncTask");
}
}
#Override
protected String doInBackground(String... params) {
//call to webservice
}
}
I am not able to get what is the problem with above code.
One more bizarre i found(bizarre may be for me only because i am new). I tried printing Thread.currentThread.getId() from both my ActivityClass as well as from my AsyncTask and surprisingly both printed "1".
If i am not wrong then that says both codes are running from the same thread.
About this i have read Running multiple AsyncTasks at the same time -- not possible? which says earlier threadpool contained only 1 thread but i am using Android 5.1 which is supposed to contain 5 threads. So again i am confused over it.
Kindly take some time to explain. Thank you
Replace this:
public CallmeGetHelperAsyncTask(AppCompatActivity activity){
this.activity=activity;
//this.dialog= dialog;
}
with:
private Context context;
public CallmeGetHelperAsyncTask(Context context){
this.context=context;
}
and this:
dialog = ProgressDialog.show(this.activity, "title", "message");
with:
dialog = ProgressDialog.show(this.context, "title", "message");
and this:
String jsonResponse=new CallmeGetHelperAsyncTask(this).execute(params).get();
with:
String jsonResponse=new CallmeGetHelperAsyncTask(LookIn.this).execute(params).get();
Although i would rather not use the static method show of the progress dialog and build an Actual Progress Dialog.
Hope it helps!!!!

Android Checking Website Updates Periodically (JSOUP)

I have a simple Android app. I am getting HTML elements from a website (article count from wikipedia) by use of JSOUP. I am getting article count on button click RefreshBtn() and show in a textview tv1 as shown below:
public class MainActivity extends ActionBarActivity {
String URL = "https://en.wikipedia.org";
Element article;
TextView tv1;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
}
private class FetchWebsiteData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(URL).userAgent("Mozilla").get();
article = doc.select("div#articlecount > a").first();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if(article == null) tv1.setText("null!");
else tv1.setText(article.text() + " articles found!");
mProgressDialog.dismiss();
}
}
public void RefreshBtn(View v) {
new FetchWebsiteData().execute();
}
...
}
I want to get article count periodically (for example in every 2 hours). Then maybe I can create push-notifications if there is a change. What is the best way to do this? I need some suggestions. Thanks.
The best way is to use the internal Alarm Manager.
Alarm Manager Example
another way is to implement a second Thread:
new Thread(new Runnable()
#Override
public void run()
{
try
{
while(true)
{
Thread.sleep(100000); //milliseconds
// Do Something
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}).start();

Categories

Resources