Android - Dialog dismiss - android

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();
}

Related

AsyncTask not working inside ViewPager

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.

Window Leaked in Async task while showing progress dialog

I have one AsyncTask I am showing progress dialog in preExecute() method of an async task and dismissing it in postExecute() method of an async task.
I am also checking if the dialog is null or not. Also set setCancelable as false to progress dialog. Tried every solution given on SO but still window is getting leaked.
Async Task :
public class RegisterUserAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
String muserName;
String mfullName;
String mpassword;
String mmobileNo;
String memailId;
String mdeviceId;
File mprofileImage;
private ProgressDialog progressDialog = null;
private static String KEY_SUCCESS = "Success";
private Context mContext;
public RegisterUserAsyncTask(Context context, String fullName, String userName, String password, String mobileNo, String emailId, String deviceId, File profileImage) {
this.mContext = context;
this.muserName = userName;
this.mpassword = password;
this.mfullName = fullName;
this.mmobileNo = mobileNo;
this.memailId = emailId;
this.mdeviceId = deviceId;
this.mprofileImage = profileImage;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
if(progressDialog == null) {
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Creating Account...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
else {
progressDialog.dismiss();
}
}
#Override
protected JSONObject doInBackground(String... params) {
try {
//Url
api = ServiceUrl.getBaseUrl() + ServiceUrl.getregister();
//Build JsonObject
jsonParams = new JSONObject();
String userName = this.muserName; // params[0] is username
String fullName = this.mfullName; // params[1] is fullname
String password = this.mpassword; // params[2] is password
String mobileNo = this.mmobileNo; // params[3] is mobile
String emailId = this.memailId; // params[4] is emailid
String deviceId = this.mdeviceId; // params[5] is deviceid
jsonParams.put("full_name", fullName);
jsonParams.put("user_name", userName);
jsonParams.put("password", password);
jsonParams.put("mobile_no", mobileNo);
jsonParams.put("email_id", emailId);
jsonParams.put("device_id", deviceId);
try {
if(convertFileToString(this.mprofileImage)!=null) {
jsonParams.put("profile_image", convertFileToString(this.mprofileImage));
System.out.println("convertFileToString(profile_image)" + convertFileToString(this.mprofileImage));
}
else
{ jsonParams.put("profile_image", " null");}
} catch (Exception e) {
System.out.println("convertFileToString(profile_image)");
}
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
if (response.has("message")) {
String message = null;
try {
if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
Toast.makeText(mContext, "success", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
progressDialog = null;
} else {
Toast.makeText(mContext, "Could not Register ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext, RegisterActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
progressDialog.dismiss();
progressDialog = null;
mContext.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In activity calling RegisterAsyncTask in onClicked method of a button in onCreate() method of an activity.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (checkValidation()) {
registerUser();
} else
Toast.makeText(RegisterActivity.this, "Form contains error", Toast.LENGTH_LONG).show();
}
});
}
private void registerUser() {
String userName = edtuserName.getText().toString();
String fullName = edtfullName.getText().toString();
String password = edtPassword.getText().toString();
String confirm = edtconfirmPassword.getText().toString();
String mobileNo = edtmobile.getText().toString();
String emailId = edtemail.getText().toString();
String deviceId = "233";
new RegisterUserAsyncTask(RegisterActivity.this, fullName, userName, password, mobileNo, emailId, deviceId,mProfileImage).execute();
}
What to do for this?
Please help. Thank you..
This problem may occurs due to "context". Progress dialog have a context of an activity but you may doing finish activity before complete the async task. So please check it once.

ProgressBar doesnt stops

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);

Calling static Async task from other fragment

I am trying to call Async task in some other activity from a fragment. I tried to call various way but none of it worked. I just want to know whats the best way to call static AsyncTask .Here is my Async task:
static class MyAsync extends AsyncTask<Void, Void, Void> {
Context context;
String username, password;
private MyAsync(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
}
ProgressDialog dialog;
private String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Connecting to Server","Getting Credentials"
, true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
ContentDownload download = new ContentDownload();
response = download.loginApi(agentId, password);
if(response.contains("Success")){
if(SettingHelper.getFirstCall(context)){
ContentDownload.CallApi(context);
SettingHelper.setFirstCall(context, false);
}
if(SettingHelper.getFirstLaunch(context)){
ContentDownload load = new ContentDownload();
load.callItemApi(context);
load.callActionApi(context);
SettingHelper.setFirstLaunch(context, false);
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(response.contains("Success")){
context.startActivity(new Intent(context, AllActivity.class));
}else{
Toast.makeText(context, "Got back", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}}
I am trying to call it this way:
LoginActivity.new MyAsync(getActivity).execute();
but its giving error
It you want to use this class from your Fragment, give it public visibility, also a public constructor and then you can call it:
new LoginActivity.MyAsync(getActivity())

warning: window already focused ignoring focus gain of com.android.internal.view. iinputmethod client $stub$proxy 4148db78

i have search and not found the answer. I want to call startActvity(newintent), but the page not change.
This my code:
public class MainActivity extends Activity {
private TextView IdPeserta, Password;
//private ArrayList<NameValuePair> authentication;
#SuppressWarnings("unused")
//private String temp, _nama = "";
//private readURL rL;
public static String username = "";
public static String password = "";
public static String status = "FALSE";
public void setPassword(String password){
MainActivity.password = password;
}
public void setUsername(String username){
MainActivity.username = username;
}
public void setStatus(String status){
MainActivity.status = status;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
IdPeserta = (TextView) findViewById(R.id.idPeserta);
Password = (TextView) findViewById(R.id.password);
}
public void Login(View view){
setUsername(IdPeserta.getText().toString());
setPassword(Password.getText().toString());
if((IdPeserta.getText().length() > 0 && Password.getText().length() > 0)){
RestTask task = new RestTask();
task.applicationContext = MainActivity.this;
task.execute();
}else{
Toast.makeText(this,"fill Id Peserta and Password 1", 0).show();
}
}
public void authenticate(){
if(status.equals("TRUE")){
Intent i = new Intent(MainActivity.this, Home.class);
//PendingIntent pending = PendingIntent.getActivity(this, 0, i, 0);
startActivity(i);
finish();
}else if(status.equals("FALSE")){
Log.d("gagal", "coba lagi");
}
}
public static String getService() {
String responseString = null;
String baseurlString = "http://10.0.2.2:8080/UjianServices/authentikasi.php";
RestClient client = new RestClient(baseurlString);
client.AddParam("id_peserta", MainActivity.username);
client.AddParam("password", MainActivity.password);
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
Log.d("error", e.getMessage());
//e.printStackTrace();
}
responseString = client.getResponse();
return responseString;
}
public class RestTask extends AsyncTask<Object, Object, Object>{
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true);
}
#Override
protected void onPostExecute(Object result) {
this.dialog.cancel();
String status = result.toString();
setStatus(status);
authenticate();
}
#Override
protected Object doInBackground(Object... arg0) {
return MainActivity.getService();
}
}
}
When i did not using the RestTask it can change the page. How i change my activity?
because applicationContext is null you have not initialize applicationContext before using it for showing ProgressDialog from onPreExecute .
you need to initialize applicationContext before using for showing ProgressDialog or just use MainActivity.this as :
#Override
protected void onPreExecute() {
applicationContext=MainActivity.this; //<<< initialize context here
this.dialog = ProgressDialog.show(applicationContext,
"Calling", "Time Service...", true);
}

Categories

Resources