I have made an application in which user log's in his accounts.For this i have used asyncTask.Everything works fine but the thing is when i get the response i want the progress bar to stop.But it goes on continously.
Async Task
protected void onPreExecute() {
super.onPreExecute ();
CommonFunctions.showProgress (c, "Please Wait", true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute (s);
try {
JSONObject jsonObject = new JSONObject (s.trim ());
JSONObject NewDataSet = jsonObject.getJSONObject ("NewDataSet");
JSONObject Table = NewDataSet.getJSONObject ("Table");
String User_ID = Table.getString ("User_ID");
String Vendor_IEntity_Code = Table.getString ("Vendor_IEntity_Code");
String Vendor_Name = Table.getString ("Vendor_Name");
// setting the preferences
SettingPreference.setUserId (c, User_ID);
SettingPreference.setVendorId (c, Vendor_IEntity_Code);
SettingPreference.setVendorName (c, Vendor_Name);
} catch (JSONException e) {
e.printStackTrace ();
}
CommonFunctions.showProgress (c, "", false);
Crouton.makeText ((android.app.Activity) c, "Login Sucessful", Style.CONFIRM).show ();
}
#Override
protected String doInBackground(String... strings) {
response = HttpRequest.post ("https://beta135.hamarisuraksha.com/web/WebService/HsJobService.asmx/IsUserValid").send ("_UserID=" + strings[0] + "&_Password=" + strings[1]).body ();
Log.e ("Login Response", "" + response);
return response;
}
CommonFunctions
public class CommonFunctions {
private Context c;
public static void showProgress(Context context, String message, boolean isVisible) {
ProgressDialog progressDialog = new ProgressDialog (context);
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
if (isVisible) {
progressDialog.show ();
} else if (isVisible == false) {
if (progressDialog.isShowing ()) {
progressDialog.dismiss ();
}
}
}
}
Problem:
ProgressDialog progressDialog = new ProgressDialog (context);
So each time you call the showProgress method you are creating a new ProgressDialog thus it is not dismissing upon calling the method again.
solution:
Create only once instance of ProgressDialog
public class CommonFunctions {
private Context c;
ProgressDialog progressDialog;
public static void showProgress(Context context, String message, boolean isVisible) {
if(progressDialog == null)
{
progressDialog = new ProgressDialog (context);
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
}
if (isVisible) {
progressDialog.show();
} else if (isVisible == false) {
if (progressDialog.isShowing ()) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
}
Problem is your creating instance again without progressdialog show. So on second time
if (progressDialog.isShowing ())
above condition is false.
I would suggest you to use this approach, since these methods are provided there for a reason.
Start your Progressbar in onPreExecute() and simply stop it in onPostexecute().
new AsyncTask<Void, Void, Void>() {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(MyActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Your Message");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Your Code
return null;
}
protected void onPostExecute(Void result) {
dialog.dismiss();
// UI updates if any
};
}.executeOnExecutor();
Try this way,hope this will help you to solve your problem.
public class CommonFunctions {
private static ProgressDialog progressDialog;
public static void showProgress(Context context, String message, boolean isVisible) {
if(progressDialog == null){
progressDialog = new ProgressDialog (context);
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
}
if (isVisible) {
progressDialog.show ();
}else{
progressDialog.dismiss ();
}
}
}
In showProgress() you are creating new object. So when you are calling this method to hide progress bar it is creating new object and hiding new one not the previous one.
You need to update CommonFunctions class as following.
public class CommonFunctions {
private Context c;
ProgressDialog progressDialog;
public CommonFunctions(Context context){
this.c = context;
progressDialog = new ProgressDialog (context);
}
public static void showProgress(String message, boolean isVisible) {
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
if (isVisible) {
progressDialog.show ();
} else if (isVisible == false) {
if (progressDialog.isShowing ()) {
progressDialog.dismiss ();
}
}
}
}
Use this as following:
CommonFunctions cf = new CommonFunctions(context);
to display progress use following:
cf.("Please Wait", true);
to hide progress use following:
cf.("", false);
Related
I am uploading some file to server using AsyncTask and I want to show a progress dialog in AsyncTask.
My AsyncTask is working fine and executing all the steps, but it never shows the dialog.I don't know what I have done wrong.
I have written below code but not working. Can someone help please!!!
Activity:
public class MainActivity extends AppCompatActivity {
ImageView videoImage ;
EditText editTextVideoTitle;
EditText editTextVideoDescription;
Button btnPostButton;
Button btnCancelButton;
private String mVideoPath;
private String mVideoThumb;
String strVideoTitle;
String strVideoDescription;
boolean videoPosted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_vid_with_desc);
editTextVideoTitle = (EditText) findViewById(R.id.videoTitle);
editTextVideoDescription = (EditText) findViewById(R.id.videoDescription);
btnPostButton = (Button) findViewById(R.id.postButton);
btnCancelButton = (Button) findViewById(R.id.cancelButton);;
mVideoPath = getIntent().getStringExtra("path");
mVideoThumb = getIntent().getStringExtra("thumb");
btnPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoPosted = postVideo();
if (videoPosted) {
Toast.makeText(getApplicationContext(), "Your video posted successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error in posting video, please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean postVideo() {
Log.i("Info", "PostVidWithDescActivity : postVideo : Start");
String strUserId = "";
String strReservedfield = "";
boolean isVideoPosted = false;
sharedPreferences = this.getSharedPreferences("com.app.rapid", Context.MODE_PRIVATE);
strVideoTitle = editTextVideoTitle.getText().toString();
strVideoDescription = editTextVideoDescription.getText().toString();
try {
strUserId = sharedPreferences.getString("userId", "");
strReservedfield = "ReservedField";
outputData = new PostToServerAsyncTask().execute(mVideoPath, strUserId, strVideoTitle, strVideoDescription, strReservedfield).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if (null != outputData && outputData.equalsIgnoreCase("200")) {
isVideoPosted = true;
} else{
isVideoPosted = false;
}
return isVideoPosted;
}
private class PostToServerAsyncTask extends AsyncTask<String, Void, String> {
private String content;
private String Error = null;
private int serverResponseCode;
Context context;
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("inputBuilder","PostToServerAsyncTask : onPreExecute Start") ;
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
//progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
progressDialog.setCancelable(false);
progressDialog.show();
Log.i("inputBuilder","PostToServerAsyncTask : onPreExecute End") ;
}
#Override
protected String doInBackground(String... inputData) {
/*
File upload code
*/
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Some string";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("inputBuilder","PostToServerAsyncTask : onPostExecute Start") ;
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
Log.i("inputBuilder","PostToServerAsyncTask : onPostExecute End") ;
}
}
}
Could you please try this?
#Override
protected void onPreExecute() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
//progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
progressDialog.setCancelable(false);
progressDialog.show();
});
}
I think the general problem is in async task, which actually is on the separate thread
I am having problem with AsyncTask class inside ViewPager's Fragment.
I have added code like below inside ViewPager's 3rd Fragment:
private View.OnClickListener finishClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
UserIdAsyncTask userIdAsyncTask = new UserIdAsyncTask( getActivity(), "URL", "Test", "Value" );
userIdAsyncTask.execute();
Her is my UserIdAsyncTask class:
private class UserIdAsyncTask extends AsyncTask<Void, Void, String> {
String url = "";
String oldpass = "";
String newpass = "";
private Context mContext = null;
private ProgressDialog dialog;
public UserIdAsyncTask( Context context, String url, String oldPass, String newPass ) {
this.mContext = context;
this.url = url;
this.oldpass = oldPass;
this.newpass = newPass;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(this.mContext, "", "Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String str = "";
try {
return str;
} catch (Exception e) {
Log.e(ThirdFrag.class.toString(), e.getMessage(), e);
}
return str;
}
#Override
protected void onPostExecute(String response) {
dialog.dismiss();
Intent i = new Intent(getActivity(), ABC.class);
startActivity(i);
getActivity().finish();
}
}
In the given code, onPreExecute() called but doInBackground() never called.
Any ideas anyone? I'm really struggling with this one.
In my android application calling an API continuously in a loop then Progress Dialog make a shadow like appearance. I think the issue is that multiple dialog running..help me to avoid this shadow. Code given below:
for(int i = indexOfSelectedId + 1 ; i < photoall_id.size(); i++)
{
all_postid.add(photoall_id.get(i));
url = URLS.BASEURL + "mobile_api.php?action=post&post_id=" +posoall_id.get(i)+user_id="+userid;
new GetImage().execute(url);
}
private class GetImage extends AsyncTask<String, Void, ArrayList<String>> {
String json = null;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
all_data=new ArrayList<>();
dialog = new ProgressDialog(FullScreenActivity.this);
dialog.setMessage("Loading Image...");
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> aVoid) {
dialog.dismiss();
all_url.add(aVoid.get(0));
}
#Override
protected ArrayList<String> doInBackground(String... params) {
JSONReader reader = new JSONReader();
json = reader.getJsonGET(params[0]);
if (json != null) {
try {
JSONObject object = new JSONObject(json);
if (object.getJSONArray("posts").getJSONObject(0).getInt("count") != 0) {
photo_url = object.getJSONArray("posts").getJSONObject(0).getString("photo_url");
}
}
Suggest a solution.Thanks in advance
To avoid multiple dialog to show:
public void showProgress(String msg)
{
if(dialog == null){
dialog = new ProgressDialog(this);
dialog.setTitle(null);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
}
if(dialog.isShowing())
{
dialog.dismiss();
}
dialog.setMessage(msg);
dialog.show();
}
public void dismissProgress()
{
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
I have created a simple login where the user enters his details and using AsyncTask it comapares user input to SQLite database if its correct it will start intent of Main activity.
Problems:
Loading progressDialog doesnt dismiss if the user password/username is incorrect but shows the else statement toast when incorrect password/username
In the Login class on the OnClick i have declared a new LoginTask of the users input here is my AysncTask
private static class LoginTask extends AsyncTask<Void, Void, Boolean> {
ProgressDialog pd;
String username, password;
private final Context context;
Intent log;
// private final WeakReference<Context> reference;
private LoginTask(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
//final Context context = this.context;
//Controller handler = new Controller(this.context);
pd = new ProgressDialog(this.context);
}
protected void onPreExecute() {
//super.onPreExecute();
pd.show(this.context,"Authenticating account ...", "Please wait ...");
pd.setCanceledOnTouchOutside(false);
}
#Override
protected Boolean doInBackground(Void... p) {
//final Context context = this.context;
Controller handler = new Controller(this.context);
handler.open();
if (!handler.executeLog(username.trim(), password.trim())){
return false;
} else {
return true;
}
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
// super.onPostExecute(result);
// final Context context = this.context;
Controller handler = new Controller(this.context);
handler.open();
if (result == false) {
Toast.makeText(context, "Failed, Incorrect Username/Password", Toast.LENGTH_SHORT).show();
} else {
handler.close();
Intent log = new Intent(this.context, MainActivity.class);
context.startActivity(log);
((Activity)context).finish();
Toast.makeText(context, "You have successfully logged on, " + username, Toast.LENGTH_LONG).show();
}
}
}
}
Change this :
protected void onPreExecute() {
//super.onPreExecute();
pd.show(this.context,"Authenticating account ...", "Please wait ...");
pd.setCanceledOnTouchOutside(false);
}
By this:
#Override
protected void onPreExecute() {
// super.onPreExecute();
this.pd.setCanceledOnTouchOutside( false );
this.pd.setCancelable( true );
this.pd.setTitle( "Authenticating account ..." );
this.pd.setMessage( "Please wait ..." );
this.pd.show();
}
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();
}});