Hello, I am trying to do what I think is a fairly simple task to authenticate a user on my server. I am using AsyncTask as a private subclass of my Activity, however when I try to populate the user object after authenticating it keeps setting it to null. Is there something strange in how the onPostExecute() method is called that is causing this? I originally had the AsyncTask as its own class but ran into the same problem, so I am try to solve this using a private subclass. Any help? Thanks.
Here is my code:
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/[email protected]&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);
}
}
}