doInTheBackground doesn't wait for function to finish? - android

I am trying to put together a login screen using the Stormpath framework in android. I used the standard Login screen provided in android studio and only modified the UserLoginTask. My problem is that it doesn't seem to wait for my call to Stormpath to finish. As soon as the class is called it goes straight in exectures doInBackground and then goes straight to onPostExecute. Here is my class:
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private boolean loginResult;
String errorMessage;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
Stormpath.login(mEmail, mPassword, new StormpathCallback<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("debug", "sucess");
loginResult = true;
}
#Override
public void onFailure(StormpathError error) {
errorMessage = error.message();
Log.d("debug", "Error: " + error.message());
loginResult = false;
}
});
return loginResult;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}

Since Stormpath.login() uses a callback, most likely it's already doing the network call on a background thread and returns you the result via the callback. If this is the case, then you don't really need an AsyncTask.

Related

Can't log out on button click on my android app

i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.

Application has stopped when click button login with ButtonLogin from android retrofit

I want making application login with Retroit. but the application always showing like keep force stop
I dont know whats happening on here
here is my function of login
private void SignInNow() {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Please wait.....");
dialog.show();
Call<Users> call = apiInterface.performLogin(username.getText().toString(), password.getText().toString());
call.enqueue(new Callback<Users>() {
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
String result = response.body().getResponse();
if(result.equals(true))
{
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(result.equals(false)) {
Toast.makeText(LoginActivity.this, "Logged in failed", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Something went wrong, Please Try Again !",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
here is my API (Register working properly)
public interface ApiInterface {
#GET("login.php")
Call<Users> performLogin(
#Query("username") String username,
#Query("password") String password
);
#GET("register.php")
Call<Users> performRegister(
#Query("Name") String Name,
#Query("username") String username,
#Query("password") String password
);
}
And this is users
public class Users {
#SerializedName("response")
private String Response;
private String Name;
private String username;
private String password;
public String getResponse() {
return Response;
}
}
did i miss something on here? like wrong API or function? thanks

How to check whether email or mobile is registered or not in Firebase

I want to implement sign up with two activities with the help of firebase, first sign up activity contains email mobile and password, and in this activity i want to check whether the entered email ID or mobile is registered or not, if it does not then move the data(i.e. email, mobile no. and password) to next activity where final registration will happen. The two methods which are present in the code i.e. userMobileExists() and userEmailExists() to check the email and mobile. But the problem is these are asynchronous so when I go to next activity then the Toast appear that email is already registered.
I am returning valid, if all the valid are true then it goes to next activity , I debugged it and it returns valid before going inside the method. It is because of asynchronous code, Please suggest something how it can be achieved on the first activity only. Or tell if I should provide the whole code.
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity";
private static final int REQUEST_SIGNUP = 0;
private Firebase mRef = new Firebase("https://abcdef.firebaseio.com/");
private User user;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
boolean valid = true;
String email;
String mobile;
String password;
#Bind(R.id.input_email)
EditText _emailText;
#Bind(R.id.input_mobile)
EditText _mobileText;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.btn_next)
Button _signupButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
//For Full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
//Back button initialization
Button backButton = (Button) findViewById(R.id.back_signup);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(), LoginActivity.class);
startActivity(in);
}
});
mAuth = FirebaseAuth.getInstance();
// mRef = Firebase(Config.FIREBASE_URL);
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
}
protected void setUpUser() {
user.setPhoneNumber(_mobileText.getText().toString());
user.setEmail(_emailText.getText().toString());
user.setPassword(_passwordText.getText().toString());
}
//private void
public void signup() {
Log.d(TAG, "Signup");
//showProgressDialog();
if (validate() && userEmailExist() && userMobileExist()) {
onSignupSuccess();
} else {
onSignupFailed();
return;
}
//_signupButton.setEnabled(false);
email = _emailText.getText().toString();
mobile = _mobileText.getText().toString();
password = _passwordText.getText().toString();
// TODO: Implement your own signup logic here.
}
public void onSignupSuccess() {
//_signupButton.setEnabled(true);
Log.d(TAG, "NEXT BUTTTON");
//hideProgressDialog();
Intent in = new Intent(this, SignupActivity2.class);
in.putExtra("Email", _emailText.getText().toString());
in.putExtra("Mobile", _mobileText.getText().toString());
startActivity(in);
/*setResult(RESULT_OK, null);
finish();*/
}
public void onSignupFailed() {
// hideProgressDialog();
Toast.makeText(getBaseContext(), "SignUp failed", Toast.LENGTH_LONG).show();
// _signupButton.setEnabled(true);
}
public boolean validate() {
email = _emailText.getText().toString();
mobile = _mobileText.getText().toString();
password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (mobile.isEmpty() || mobile.length() != 10) {
_mobileText.setError("Enter Valid Mobile Number");
valid = false;
} else {
_mobileText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
public boolean userEmailExist() {
//private Firebase mRef = new Firebase("https://.firebaseio.com/users/");
mRef.child("users").orderByChild("email").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue()== _emailText.getText().toString()) {
Toast.makeText(getBaseContext(), "Email already exist. Please choose a different one", Toast.LENGTH_SHORT).show();
_emailText.setError("Email already exist. Please choose a different one");
valid = false;
} else {
email = _emailText.getText().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return valid;
}
public boolean userMobileExist() {
mRef.child("users").
orderByChild("cellPhone").equalTo(_mobileText.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
_mobileText.setError("Mobile Number already exist");
valid = false;
} else {
mobile = _mobileText.getText().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return valid;
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void showProgressDialog(){
if(mProgressDialog == null){
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog(){
if(mProgressDialog != null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
}
You need to grasp the concept of callbacks. You cannot return a variable that's assigned asynchronously.
As a quick solution to your problem, start with an interface
public interface OnUserActionListener {
void onExists(Boolean exists);
}
Then, make your methods be void and accept a parameter
public void userEmailExist(final String email, final OnUserActionListener listener) {
mRef.child("users")
.orderByChild("email")
.equalTo(email)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listener.onExists( dataSnapshot.exists() );
}
...
// no return statement
}
Then, when you call that method, you can pass in the string value you want to search for, and implement your interface.
So replace this synchronous code
validate() && userEmailExist()
With the async version
if (validate()) { // This is synchonous
final String email = _emailText.getText().toString();
final String mobile = _mobileText.getText().toString();
// This is asynchronous
userEmailExist(email, new OnUserActionListener() {
#Override
public void onExists(Boolean exists) {
if (exists) {
Toast.makeText(getBaseContext(), "Email already exist. Please choose a different one", Toast.LENGTH_SHORT).show();
_emailText.setError("Email already exist. Please choose a different one");
onSignupFailed();
} else {
onSignupSuccess();
}
}
});
However you choose to define that interface is up to you
And again, worth repeating, don't assign a field valid within your callbacks. Try your best to implement all logic requiring a value to the callback itself
You can also implement the entire interface on the class, which is what I would recommend in this scenario as a SignUpActivity because you want to listen for user event actions such as success or error
Just an example using the method names you already have
public interface OnUserActionListener {
// Combine the email and phone into one action
void onUserExists(User user, Boolean exists);
void onSignupSuccess(User user);
void onSignupFailed(String reason);
}
public class SignupActivity extends AppCompatActivity
implements OnUserActionListner { // Implement this interface
// Define the needed methods
#Override
public void onUserExists(User user, Boolean exists) {
if (exists) {
onSignupFailed("User " + user + " already exists");
} else {
onSignupSuccess(user);
}
}
#Override
public void onSignupSuccess(User user) {
// Do something
}
#Override
public void onSignupFailed(String reason) {
Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle b) {
...
}
etc. etc.
Then, that other method call simply becomes.
if (validate()) { // This is synchonous
final String email = _emailText.getText().toString();
final String mobile = _mobileText.getText().toString();
// This is asynchronous & you defined the Activity as the interface
userEmailExist(email, SignupActivity.this);
I'm not satisfied with the accepted answer because when I used it in my project it still failed. After trying many thing I write my own code ... and it is working. If you want check whether user is already registered or not you can try the following code.
private void isUserAlreadySignUp(String phone){
firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("authUser");
// after getting reference of child, checked orderbykey so we get if phone is key we can get ref in dataSnapshot...
databaseReference.child( "userPhone" ).orderByKey().equalTo( phone ).addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Boolean isExists = dataSnapshot.exists();
if (isExists)
showToast( "This number is alredy Registerd..!!" );
else
{
// if mobile is not registered you can go ahead...
// You can write your further code here or call methods...
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
showToast("Error :" + databaseError);
wSignUpProgressBar.setVisibility( View.GONE );
}
} );
}
// For Toast msg...
private void showToast(String s){ Toast.makeText( getActivity(), s , Toast.LENGTH_SHORT ).show(); }
To register a users mobile number on the database after authenticating the user, you can call this method.
// Register User on the database --------------------------
private void registerUserOnDatabase( String userPhone){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("authUser").child("userPhone");
userRef.child( userPhone ).setValue( userPhone );
}

How to save a variable in AsyncTask in Android

I am using Twitter 4j to post tweet on single button. If user revoke access of my app then its showing Error in Logcat in do in background i want this error and if this error comes my another hide button of twitter authorize app visible. how do i do that please help. I need that error and if its exists i want to hide show my buttons.
class updateTwitterStatus extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(String... args) {
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate statusUpdate = new StatusUpdate(status);
File extStore = Environment.getExternalStoragePublicDirectory("/Twitter/Cache/demo.jpg");
statusUpdate.setMedia(extStore);
twitter4j.Status response = twitter.updateStatus(statusUpdate);
} catch (TwitterException e) {
Log.d("Failed to post!", e.getMessage());
error=e; //error is exception
}
return null;}
#Override
protected void onPostExecute(Void result) {
pDialog.dismiss();
Toast.makeText(getContext(), "Posted to Twitter!"+error, Toast.LENGTH_SHORT).show();
/* i need a variable like int a =10; access it globally, How i do that/*
} } }
You can save the exception in a variable and check it in onPostExecute()
and hide your button ..
new AsyncTask<Void, Void, Boolean>() {
Exception error;
#Override
protected Boolean doInBackground(Void... params) {
try {
// do work
return true;
} catch (Exception e) {
error = e;
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(ctx, "Success!",
Toast.LENGTH_SHORT).show();
} else {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_SHORT).show();
//error occurs hide button here
}
}
}
}

Retrofit 2 - How show progress bar async?

I created a default login activity when creating a new project in Android.
By default creates a progressBar that works well to login and displayed correctly. All this makes it through AsyncTask.
Now I used Retrofit 2 to make way Async login.
When I pushed the button login launched a method that content:
....
....
showProgress(true);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, retrofit2.Response<User> response) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
User userdatos = response.body();
if(userdatos != null){
// redirect to Main Activity page
showProgress(false);
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
}
else{
showProgress(false);
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
call.cancel();
showProgress(false);
Toast.makeText(LoginActivity.this, "Please check your network connection and internet permission", Toast.LENGTH_LONG).show();
}
});
I forced a Thread.sleep (3000) to check.
No progress bar appears, and the debug shows:
Skipped 180 frames! The application May be doing too much work on ITS main thread.
How can this be solved?
I will have many Async calls where I would always display a progress bar to wait for the response is complete.
Thank you
Let me share with you mine code implementation for default Login activity created by Android Studio and my Retrofit implementation. Default login activity, consist AsyncTask which called UserLoginTask, inside it, I did all my login logic stuff. I am using .execute instead of .enqueue because it synchronous and we don't need new thread inside AsyncTask
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Constants.ROOT_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
Call<JsonElement> result = service.getToken(mEmail, mPassword, "password");
try {
//using sync request and get response
JsonElement element = result.execute().body();
if(element!=null) {
//do whatever you want with your response
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
if(clientType != 2){
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
clientType = 0;
}
else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(intent, 1);
}
// finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
Shameless Promotion
I've created RxLoading library for that, it can do this and much more,
you can just do something like this:
networkCall().compose(RxLoading.<>create(loadingLayout)).subscribe(...);
it consists out of 2 classes, a custom view (loadingLayout) and RxLoading which is a transformer that glue it all together, you can choose to work with both or either of them.
you need to be using retrofit2 with RxJava though.
RxLoading also supports empty and error states (with built-in retry mechanism, so make sure to check this options as well)
you can find out more on the GitHub page.

Categories

Resources