Progress Dialog only shows up when the job is already done - android

I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.

If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?

I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}

Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});

Related

Android - AsyncTask inside Fragment doesn't work in Marshmallow

I created an AsyncTask to fetch scores. It shows the progressdialog for a split-sec and then disappears. The doInBackground method never gets executes. This task is called inside a fragment.
private class GetScore extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute() {
final ProgressDialog show = progressDialog.show(getActivity(), "", yourName);
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
scoreMap = ScoreCalc.getEngScore(yourName);
// Toast.makeText(LoveActivity.this, engageMap.toString(), Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(String img) {
}
}
.
.
.
.
.
.
.
private void confirmYes() {
String s =mEditText.getText().toString();
if(s.equals(""))
return;
new GetScore().execute();
}
Help?
use this asynctask class instead of your class.
public class GetScore extends AsyncTask<String, Void, String>
{
String method;
#Override
protected String doInBackground(String... arg0)
{
method = arg0[0];
return getData.callWebService(arg0[0], arg0[1]);
}
protected void onPostExecute(String xmlResponse)
{
if(xmlResponse.equals("") )
{
try{
if(progDialog!=null && progDialog.isShowing()){
progDialog.dismiss();
}
}catch(Exception ex){}
Toast.
}
else
{
if (method.equals("methodname"))
{
MethodName(xmlResponse, "ResponseTag");
try{
if(progDialog!=null && progDialog.isShowing()){
progDialog.dismiss();
}
}catch(Exception ex){}
//What Ever Want to Do
}
}
}
}
}

prograss bar not displaying using AsyncTask in android

I just wrote a code that need to show progress bar when ever interacting with server.but it is not working if i call dismiss method in below code.
public class AsyncClass extends AsyncTask<String, String, String> {
String result;
public ProgressDialog progressbar;
static Context context;
public AsyncClass(Context context,String result) {
this.context = context;
this.result = result;
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
URI u = new URI(params[0]);
// url = Urls.SENDMOVIE_REQUEST_URL;
HttpGet HG = new HttpGet(u);
HttpResponse response = httpclient.execute(HG);
//httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(response.getEntity());
Log.d("result", result);
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPreExecute() {
progressbar = new ProgressDialog(context);
progressbar.setCancelable(true);
progressbar.setMessage("loading....");
progressbar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressbar.setProgress(0);
progressbar.show();
}
#Override
protected void onPostExecute(String result) {
progressbar.dismiss();
}
}
I think its not showing because of progressbar.setProgress(0);
just remove it & try.
And If you want progressUpdates you need to do like this:
private class DownloadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Edited Iqbal's answer
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(){
dialog = new ProgressDialog(HomeActivity.this);
dialog.setCancelable(false);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
/** * Write your code */
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
}
}
}
Use this below code it shall do the job for you
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
/** * Write your code */
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
}
}
}
Edit:
Add the initialization of progress bar in the constructor as
public AsyncClass(Context context,String result) {
this.context = context;
this.result = result;
progressbar = new ProgressDialog(context);
}
And remove it from internecine().

Get all JSON response and then start another activity

I am doing socket programming and getting JSON response. Everything is working perfectly but the only thing that is getting me in trouble is that I start another activity before getting response but I want to get all response and after that start another activity.
Here is my code.
jsonobject1.put("username", edt.getText().toString());
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4");
try {
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
In my above code I am sending JSON data to server and getting JSON object in response. But before getting the response I am being sent to another activity. So I first want response and then start activity. Help me with some pseudo code.
Thanks
Create an AsyncTask class
public class GetJSONResult extends AsyncTask<String, Void, Void>
{
ProgressDialog pd ;
private Context _context;
public GetJSONResult(Context c)
{
_context = c;
}
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(_context);
pd.setTitle("Getting JSON details");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
jsonobject1.put("username", params[0]); // params[0] is the value passed i.e edittext value
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4")
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
}
catch (Exception e)
{
if (pd.isShowing())
pd.dismiss();
}
return null;
}
protected void onPostExecute(Void v)
{
super.onPostExecute(v);
try
{
if (pd.isShowing())
pd.dismiss();
}
catch(Exception e)
{
}
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
}
}
Form your MainActivity call the AsyncTask like this
public MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// First get the reference to EditText using findViewById, then
String s = edt.getText().toString();
// Call the AsyncTask
new GetJSONResult(MainActivity.this).execute(s); // pass the edittext value to doInBackGround method.
}
}
private class getResponse extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonobject1.put("username", edt.getText().toString());
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4");
try {
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
}
#Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
and for executing new getResponse().execute();

ProgressDialog is showing after doInBackground() finished in android

I want to show the progressdialog when the webservice is called and stop the dialog on request is finished.
I did the following way but the dialog showing after the web service request is finished.
public class NetWorkRunTask extends AsyncTask<String, Void, String> {
Context ctx;
public NetWorkRunTask(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(ctx);
}
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog.setMessage("Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//contactService.getAssetsAtFirstRun();
// mProgressDialog.show();
return ServerConnection.getXmlRespFromUrl(params[0]); //this will include HttpPost
//return null;
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
}
and in onClickListener
String xml=null;
try {
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null).get();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
what's going wrong here.....
just do this in your asynk task
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
}
Remove the get() method, while calling your async task
change
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null).get();
to
xml =new NetWorkRunTask().execute(finalURL,null,null);
and
public class NetWorkRunTask extends AsyncTask {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//contactService.getAssetsAtFirstRun();
return ServerConnection.getXmlRespFromUrl(params[0]); //this will include HttpPost
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
In your code you are calling 'get()' method. [get() -waits if necessary for the computation to complete"].
Replace your Asynch task calling line with the below code and try
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null);
You can define an interface in your Async task
public interface OnProcessCompleteListener{
public void onSuccess(String result);
public void onFailure();
}
and in your activity class you can implement the call back methods and can return results to the class.
OnProcessCompleteListener listener = listener = new OnProcessCompleteListener() {
#Override
public void onSuccess(String result) {
// do what u want
}
#Override
public void onFailure() {
}
};
Pass the 'listener' to the AsyncTask and call the onSuccess(String result), onFailure() methods where u want.
#Override
protected void onPostExecute(String result) {
if(result != null) {
listner.onSuccess(result);
}else{
listner.onFailure();
}
if(mProgressDialog != null){
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}

How can I add a progress dialog in AsyncTask with minimum loading time (2sec)

When user clicks button, will go to Activity B from Activity A.
However, since in Activity B, data will be downloaded from Internet, I would like to add a progress dialog.
Sometimes, the connection will be very fast, less than one second and sometimes will be more than 5 seconds.
If the progress dialog shows <1 sec, I think it is very bad for user experience.
So, I would like to add a minimum loading time, for example, 2 seconds.
That means even the loading time is less than 2 seconds, the progress dialog will also at least show 2 seconds.
Is there any ways to do so?
you can use Below Code. Pass Time and Object of your Dialog here.
public void timerDelayRemoveDialog(long time, final Dialog d){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
d.dismiss();
}
}, time);
}
EDITED
you can Use this Sample Code :
class LoginProgressTask extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return Boolean.TRUE; // Return your real result here
}
#Override
protected void onPreExecute() {
showDialog(AUTHORIZING_DIALOG);
}
#Override
protected void onPostExecute(Boolean result) {
// result is the value returned from doInBackground
removeDialog(AUTHORIZING_DIALOG);
Intent i = new Intent(HelloAndroid.this, LandingActivity.class);
startActivity(i);
}
}
My solution (worked well):
private class ProgressTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
long timestamp1;
long timestamp2;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(YOUR_CONTEXT);
dialog.setCancelable(false);
dialog.setMessage("Please wait...");
dialog.show();
timestamp1 = System.currentTimeMillis();
}
#Override
protected Void doInBackground(Void... params) {
//doSomething ...
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//doSomething ...
timestamp2 = System.currentTimeMillis();
long timeDifference = timestamp2 - timestamp1;
if (timeDifference >= 2000) {
dialog.dismiss();
} else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 2000 - timeDifference);
}
}
}
Here is another version. Using SystemClock does not require try catch block.
ParentActivity.this is the context where Task is executed.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.SystemClock;
protected class Task extends AsyncTask< String, Void, String >
{
private ProgressDialog mDialog = new ProgressDialog( ParentActivity.this );
private long mTaskStartTimeMills;
protected void onPreExecute()
{
mTaskStartTimeMills = System.currentTimeMillis();
mDialog.setMessage( "Loading.." );
mDialog.show();
}
protected String doInBackground( String... arg )
{
// TODO
return null;
}
protected void onPostExecute( String json )
{
final long timeToWait = 1000 - ( System.currentTimeMillis() - mTaskStartTimeMills );
if ( timeToWait > 0 )
{
SystemClock.sleep( timeToWait );
}
mDialog.dismiss();
}
}
this may helps you
new AsyncTask<Void, Void, Void>() {
ProgressDialog mDialog;
ArrayList<String> files;
#Override
protected void onPreExecute() {
mDialog = new ProgressDialog(MyMainAct.this);
mDialog.setMessage("Loading");
mDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// do your work here
Log.i("Share Media MyMainAct", " newFiles is called path is - " + path +"/" + spndirectory.getSelectedItem().toString());
files = getFiles(path + "/" + spndirectory.getSelectedItem().toString());
return null;
}
#Override
protected void onPostExecute(Void result){
if (mDialog != null && mDialog.isShowing()){
mDialog.dismiss();
}
setFileAdapter(files);
}
}.execute();

Categories

Resources