我正在尝试执行我认为在我的服务器上对用户进行身份验证的相当简单的任务。我使用AsyncTask作为我的Activity的私有子类,但是当我尝试在验证后填充用户对象时,它会将其设置为null。是如何调用onPostExecute()方法引起这种情况的?我最初将AsyncTask作为自己的类,但遇到了同样的问题,所以我尝试使用私有子类来解决这个问题。有帮助吗?感谢。
这是我的代码:
public class Testing extends Activity {
private User user;
public User getUser() {
return this.user;
}
public void setUser(User value) {
this.user = value;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView iconImage = (ImageView) this.findViewById(R.id.image);
final Button testButton = (Button) this.findViewById(R.id.testButton);
final TextView text = (TextView) this.findViewById(R.id.text);
iconImage.setImageResource(R.drawable.logo_real);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LoginTask loginTask = (LoginTask) new LoginTask().execute(new Void[0]);
text.setText(user.getFormattedFullName());
}
});
}
private class LoginTask extends AsyncTask<Void, Void, User> {
public LoginTask() {
}
protected User doInBackground(Void... params) {
User newUser = new User();
try {
System.out.println("testing task");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://10.0.2.2:8080/Dugout/androidLogin?LOGIN_ID=test@gmail.com&PASSWORD=password");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String message = "";
String inputLine = "";
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
while ((inputLine = bf.readLine()) != null) message+=inputLine;
JSONObject returnedUser = new JSONObject(message);
int userId = returnedUser.getInt("userId");
boolean loginSuccess = returnedUser.getBoolean("login_success");
String firstName = returnedUser.getString("firstName");
String lastName = returnedUser.getString("lastName");
newUser.setId(userId);
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
newUser.setLoginSuccess(loginSuccess);
return newUser;
} catch (Exception e) {
newUser.setLoginSuccess(false);
return newUser;
}
}
protected void onPostExecute(User user) {
setUser(user);
}
}
}
答案 0 :(得分:2)
应该是
protected void onPostExecute(User user) {
text.setText(user.getFormattedFullName());
}
您试图在user
创建AsyncTask
之前访问doInBackground(..)
(整点是{{1}}在后台线程中运行,因此不会阻止UI线程。)