Reputation: 321
I beginner to programming Android, I declared Boolean flag
, I want to be set true or false in the inner class and return flag
, but android studio say you should declare final!!!i don't want to declare final because i set true or false in variableflag
.
My question is, What should I do right
Upvotes: 1
Views: 1935
Reputation: 7290
Answering your literal question:
An inner class doesn't really get access to the outside variables (like your flag
), Java only creates the illusion of access.
Technically, you get a field named flag
(automatically created invisibly by the compiler) with a copy of the flag
variable's content from the moment you instantiate the inner class. It's similar to passing flag
as an additional argument into the constructor and storing it in a local field of the same name.
But then, to not destroy the illusion of access to your flag
variable, Java forbids you to change flag
, as technically only the local field could be changed, not the outside variable.
So, a solution for that part (already mentioned by others) is to have a boolean[] flagHolder = new boolean[1];
and use flag[0]
for communication.
But that won't help you in your use case.
When the onResponse()
method is called (when receiving your response), your https()
method has most probably already returned, so it won't be able to see anything that might result from the later response.
Some formal remark:
Please, don't show code as screenshots (it's against the stackoverflow rules), but copy it into your question as text. That makes it easier for us to make our own tests and improvements...
Upvotes: 1
Reputation: 5392
You can't return a boolean in a method that is making an asynchronous call to retrieve that return value.
Instead make an interface inside this class, and include an inline implementation of that interface as part of the method signature and call back on success or error.
public class yourHTTPClass{
public void yourMethod(myCallbacks callback){
doAsyncCall(){
onSuccess(){
callback.onSuccess();
}
}
}
public interface myCallbacks{
onSuccess();
onError();
}
}
public class OtherClass{
yourHTTPClassInstance.yourMethod(new myCallbacks(){
@Override
public void onSuccess(){
}
@Override
public void onError(){
}
}
}
The above is PSEUDO CODE. do NOT copy and paste it. Do not point out that it doesn't compile lol. Just showing you implementation for a call back :). Hope that helps.
Upvotes: 1
Reputation: 1125
You can do this by declaring an array :
final boolean[] flag = {false};
And in your onResponse set the value:
flag[0] = true;
Android Studio automatically propose this solution when you click on the help tooltip.
Upvotes: 1
Reputation: 28228
The request you are doing is async, meaning it will always return false. By the time the result method is called, the value has already been returned. Use callback methods instead for getting the result from an async call
Upvotes: 1