对于下面给出的代码,字符串 receivedResponse
从接口函数调用时不会立即指定。我发现,分配字符串 response
在 receivedResponse
,我必须调用函数 onCurrentResponse()
再一次。我将非常感激知道背后的原因。如果有可能以某种方式解决这个问题,那就更好了。以下代码足以再现错误。请看一下:
public class MainActivity extends AppCompatActivity {
private NetworkManager networkManager;
String receivedResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkManager = new NetworkManager(this);
}
public void handleClick(View view){
networkManager.getResponseFromNetwork(callback);
System.out.println("Response in 'receivedResponse' is: " + receivedResponse); // I am getting
//null value when called for the first time
}
private final NetworkManager.ServiceCallback callback = new NetworkManager.ServiceCallback() {
@Override
public void onCurrentResponse(@NonNull String response) {
receivedResponse = response; // I have to call this function again to assign the response
string
System.out.println("Response in 'response' is: " + response);
}
};
}
class NetworkManager {
private final RequestQueue queue;
public NetworkManager(@NonNull final Activity activity) {
queue = Volley.newRequestQueue(activity.getApplicationContext());
}
public interface ServiceCallback {
@MainThread
void onCurrentResponse(@NonNull final String response);
}
public void getResponseFromNetwork(final ServiceCallback callback) {
final String url = "https://www.themealdb.com/api/json/v1/1/random.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
callback::onCurrentResponse, error -> System.out.println("Some error")
);
queue.add(stringRequest);
}
}
暂无答案!
目前还没有任何答案,快来回答吧!