Issue
Im looking solution for my problem.
I call an AsyncTask
in my Activity
:
login.execute(emailText.getText().toString(), passwordText.getText().toString());
In class Login i checking, if user exist.
public class Login extends AsyncTask<String, Boolean, Void> {
public Login(Application application){
repository = new Repository(application);
}
@Override
protected Boolean doInBackground(String... body){
try {
user = repository.getUser(body[0], body[1]);
if (user != null)
return true; //wont work
else {
return false;
}
}
catch(Exception e){
return null;
}
}
protected void onPostExecute(Long result) {
//i want to have bool value here that i will see in my activity
}
My question is, how to get bool
value from AsyncTask
when condition in if match? If it is any possible way to call method like that?
boolean valid = login.execute();
Thanks for help
Solution
Change the onPostExecute()
argument type to Boolean
and then tell who would be interested in the result what happened.
For this last part you can have an interface and have that someone (intereste class) implement it.
public class Login extends AsyncTask<String, Boolean, Boolean> {
private LoginListener listener;
public Login(Application application, LoginListener listener){
repository = new Repository(application);
this.listener = listener;
}
@Override
protected Boolean doInBackground(String... body){
try {
user = repository.getUser(body[0], body[1]);
if (user != null)
return true; //wont work
else {
return false;
}
}
catch(Exception e){
return null;
}
}
protected void onPostExecute(Boolean result) {
listener.onLoginPerformed(result)
}
public static interface LoginListener{
public void onLoginPerformed(Boolean result);
}
}
Then suppose you want MainActivity to react upon the login:
public class MainActivity extends AppCompatActitvity implements LoginListener{
....
// When you create the Login object, in onCreate() for example:
// new Login(application, this); // this is the activity acting as listener...
@Override public void onLoginPerformed(Boolean result){
// do what you want to do with the result in Main Activity
}
}
Answered By - Juan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.