问题
I have a little problem, I have a AsyncTask where I get a response from the server if the user is registered or not, would that after the call, if the user accesses exist in another fragment, also by storing in a preferences user email, however I have problem when I call getFragmentManager()
, could someone help me out? Thank you. This is my code.
LoginTask.java
public class LoginTask extends AsyncTask<String, Void, User> {
public LoginTask() {
}
@Override
protected User doInBackground(String... params) {
User user = new User();
user.setEmail(params[1]);
user.setPassword(params[2]);
// Set the Content-Type header
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application", "json"));
HttpEntity<User> requestEntity = new HttpEntity<User>(user, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// Make the HTTP POST request, marshaling the request to JSON, and the response to a String
ResponseEntity<User> responseEntity = restTemplate.exchange(params[0], HttpMethod.POST, requestEntity, User.class);
return responseEntity.getBody();
}
@Override
protected void onPostExecute(User user) {
if (user.getSuccess()){
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new AreaRiservataFragment()).commit();
}else{
}
}
}
I get the error: Cannot Resolve Method 'getFragmentManager()'
.
回答1:
The best solution might be to make your AsyncTask
a nested class of your activity.
public class YourActivity extends Activity {
...
class LoginTask extends AsyncTask<String, Void, User> {
...
@Override
protected User doInBackground(String... params) {
...
}
@Override
protected void onPostExecute(User user) {
...
}
}
}
If it is not possible for you, you can pass your activity as a parameter to AsyncTask
. Have a look at the good example Access instance variables from an activity inside a AsyncTask.
来源:https://stackoverflow.com/questions/35828794/call-a-fragment-in-asyncktask-onpostexecute-method